I have two simple HTML forms on one page. I want to create Django view to submit multiple Django forms. I can submit form1 but I have no clue how to submit form2.
There is lot of material on internet but they are all about Djanog forms. Please help me with HTML form submission.
HTML Form
<form action="" method=post name="form1" id="form1">
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
</form>
<form action="" method=post name="form2" id="form2">
<input type="text" id="form2" name="form2">
<button type="submit">Submit</button>
</form>
Views.py
def index(request):
if request.method == 'POST':
input_form1 = request.POST.get('input_form1')
return render(request, 'index.html', params)
Please elaborate how to integrate form2 in Views.py
you can put hidden input inside of each form to identify them
index.html
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_1">
</form>
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form2" name="form2">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_2">
</form>
views.py
def index(request):
if request.method == 'POST':
#watch output in console
print(request.POST)
which_form_is_submiting = request.POST["which_form_is_it"]
if str(which_form_is_submiting) == "this_is_form_1":
#here is yor logic for data from form 1
form_1_input = request.POST["input_form1"]
if str(which_form_is_submiting) == "this_is_form_2":
#here is your logic for data from form 2
form_2_input = request.POST["input_form2"]
return render(request, 'index.html', params)
Related
I'm trying to create a delete button in my template:
<button type="submit" class="btn btn-danger" value={{ instance.name }}> Delete </button>
And I want this button to submit that data in my views.py :
instance_client = compute_v1.InstancesClient()
if request.method == "POST":
instance = request.POST['data']
instance_client.delete(project='xxx', zone='xxx', instance=HERE_I_WANT_THE_DATA)
It's a script that will delete an instance from gcloud.
But I don't know exactly how to deliver the data from the template to views.py.
I'm using Bootstrap 5.
Hope I understand your question.
Template
<form action="{% url 'delete_function' item.id %}" method="POST">
{% csrf_token %}
Cancel
<input class="btn btn-sm btn-danger" type="submit" value="Delete">
</form>
Views
def deleteFunction(request, pk):
item = Model.objects.get(id=pk)
if request.method == "POST":
item.delete()
return redirect('/')
url
path('delete_function/<str:pk>', views.deleteFunction, name='delete_function')
In my HTML-file I have a submit button (click_button) to do stuff and a submit button for a Django form (form_submit).
All submits are redirected to one View-function (get_post_from_submit). If using the return render() function, I always have to return the context including the form, but I have no information of the form when I pressed the click_button.
Is there any way to not return the form again?
home.html
....
<body>
{% load bootstrap4 %}
<form action="" method="POST" novalidate>
{% csrf_token %}
{% bootstrap_form form %}
</form>
<form action="" method="POST" novalidate>
{% csrf_token %}
<button class="btn btn-primary" name="click_button" type="submit">Grafik</button>
</form>
</body>
....
views.py
def get_post_from_submit(request):
if request.method == 'POST':
if "book_field" in request.POST:
# Do Stuff
form = form_book(request.POST)
if "click_button" in request.POST:
# Do Stuff
# Here the form always gets a reset, because I have no Info about the form in POST but it is needed as context...
form = form_book()
return render(request, 'home.html',{"form": form})
One method would be to encapsulate just one form tag across both sections.
<form action="" method="POST" novalidate>
{% bootstrap_form form %}
<input type="submit" name="action" value="FormSubmit"/>
{% csrf_token %}
<input type="submit" name="action" value="Grafik"/>
</form>
Using name="action" you can differentiate the POST action in the view like so:
def get_post_from_submit(request):
if request.method == 'POST':
form = form_book(request.POST)
if request.POST['action'] == 'FormSubmit':
[...]
elif request.POST['action'] == 'Grafik':
[...]
return render(request, 'home.html',{"form": form})
The form_book will no be able to retain the form data whenever the Grafik POST type is send to the view.
I want to get some user input, process it a little and present the same to the user. I need not save the inout to the database. What is the simplest way to do that in Django
In the html template
<form method="POST">
{% csrf_token %}
{{ form.name of field in forms.py }}
</form>
In the views.py
if request.POST:
form = formName(request.POST)
if form.is_valid():
variable: form.cleaned_data['name of field in forms.py']
this is a simple example
views.py
def test_form(request):
if request.method == "POST":
user = request.POST.get('username')
if user == "mark":
return HttpResponse('hello mark')
return render(request, "form.html")
urls.py
path ('form/', test_form, name="form")
form.html
<form method="POST" action="{% url 'form' %}">{% csrf_token %}
<input type="text" name="username">
<input type="submit" name="submit">
</form>
Sorry for asking similar questions, but other similar questions/answers do not help me with Django 2.
Question:
I have two actions, one is to show some data as a table.
In the second form, I edit this data and will save it as a table using Django in the database. Here is some code:
simple_upload.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile" value="formOne">
<button class="btn btn-primary" type="submit">Upload</button>
</form>
second form:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="mytable" value="formTwo">
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
...
</tbody>
</table>
<input type="submit" value="Submit">
</form>
views.py
def simple_upload(request):
if request.method == 'POST':
...
if request.is_ajax():
return render(request,
'project/simple_upload.html',
{'section': 'project', 'lines': zipped})
return render(request,
'project/list.html',
{'section': 'project', 'lines': zipped})
return render(request, 'project/simple_upload.html')
urls.py:
urlpatterns = [
...
path('', views.simple_upload, name='list'),
...
]
list.html:
...
{% include "project/simple_upload.html" %}
...
In this case, only the first form works, the second one fails.
Question 1: Can I do if request.method == 'POST' and formOne in request.POST:", I try but it does not react at all.
Question2: How can I write two methods and assign them using urls.py?
To show the data in a table, you can try Tables2 in Django, this might make things easier for you
Also in your case, you might need to make different views for different forms, Since both of them make a POST request, it will be difficult to differentiate.
You can easily do that by specifying action attribute in form tag.
Form 1
<form id="form1" method="post" action="view/for/form/1" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile" value="formOne">
<button class="btn btn-primary" type="submit">Upload</button>
</form>
Form 2
<form method="post" action = "view/for/form/2" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="mytable" value="formTwo">
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
...
</tbody>
</table>
<input type="submit" value="Submit">
</form>
Later you can redirect using json responses to avoid refreshing the page
in your urls.py add
url('view/for/form/2', save_form, name='save'),
in your views.py
def save_form(request):
#your save logic using request.post
return redirect('your/current/url')
i have created a form with minimal fields(for testing) , but it never enters form.is_valid()
Here is the minimal code
in the models.py
from django.db import models
class sample(models.Model):
field1=models.CharField(max_length=100)
field2=models.CharField(max_length=100)
in the forms.py
from django.forms import ModelForm
from app.models import sample
class someform(ModelForm):
class Meta:
model=sample
in the views.py
some imports
def index(request):
return render(request, 'app/index.html')
def contact(request):
if request.method=='POST':
form=someform(request.POST)
if form.is_valid():
field1=form.cleaned_data['field1']
field2=form.cleaned_data['field2']
return HttpResponse("valid")
else:
return HttpResponse("invalid")
else:
form=someform()
return HttpResponse("error")
The problem is , it never enters (if form.is_valid()) . Am i missing something ? please help
in the index.html
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input type="submit" id="submit" name="submit">
</form></body></html>
First pass your form to index.html, when the request is not POST in views.py:
else:
form=someform()
return render(request, 'index.html', locals())
In template you should make it like this:
<form action="contact" method="POST" xmlns="http://www.w3.org/1999/html">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn">Submit</button>
</form>
When receiving the POST query, Django is looking for the 2 fields of IDs id_field1 and id_field2, litteraly, thus your HTML is to be the following:
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="id_field1" name="field1">
<input type="text" id="id_field2" name="field2">
<input type="submit" id="submit" name="submit">
</form>
</body>
</html>
Another solution is to use the {{ form.as_p }} or {{ form.as_table }} to render the inputs inside or tags automatically.
You could also add {{ form.non_field_errors }}, {{ form.field1.errors }}, and {{ form.field2.errors }} in your current HTML to display the form errors when validation fails.