Django form with checkbox is always False - python

I'm looking to create a Django form with a checkbox.Irrespective of weather I check or uncheck the box,it is not detected in POST request.Here is the code of the template-
<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
Here is my forms.py-
from django import forms
class AnnotateForm(forms.Form):
repeat=forms.BooleanField(required=False)
Here is my views logic-
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["repeat"])#Always false
Irrespective of weather the checkbox is checked or not,the print statement always gives False.
I know there are questions similar,but they don't solve my problem.

<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" name="something" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
and in view
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["something"])#Always false
you need to give a name in the input field or else it wont be captured

Related

Django - pass value from html template to python function

I am trying to spin first Django project and I am struggling how to pass value to python function from html. Basically, I have 1 placeholder with 3 buttons next to it.
I have file.html in templates.
<form method="POST" action="">
{% csrf_token %}
<input type="text" name="name_id" placeholder="placeholder value"/>
<input type="submit" value="Value 1"/>
<input type="submit" value="Value 2"/>
<input type="submit" value="Value 3"/>
</form>
I am trying to pass placeholder value to views.py. In views.py I have 3 functions. I want to execute only one of them based on value.
Value 1 from file html triggers function 1 in views py
Value 2 from file html triggers function 2 in views py
Value 3 from file html triggers function 3 in views py
I am not sure how to handle urls.py
All files are in same app/folder
Any help is much appreciated.
You can work with a name="…" attribute on the submit <button>s:
<form method="POST" action="">
{% csrf_token %}
<input type="text" name="name_id" placeholder="placeholder value"/>
<input type="submit" name="value1"/>
<input type="submit" name="value2"/>
<input type="submit" name="value3"/>
</form>
In the view you can then check with:
def some_view(request):
if request.method == 'POST':
if 'value1' in request.POST:
# …
pass
elif 'value2' in request.POST:
# …
pass
elif 'value3' in request.POST:
# …
pass

how can i insert dynamic fields of a form in django into database

I have a form with checkbox inputs the number of inputs is dynamic because i get it from the database,in my form i might have 2 or 3 or N .. checkboxes. From these input the user will check some or all of them and then he click the submit button.
The problem is that only one input is saved into database
<form method="post" action="createQcm">
{% csrf_token %}
{% for mati in quest %}
<INPUT type="checkbox" value ="{{mati.id_question }}" name="choix" >
{{mati.questionA }}</input></br></br>
{% endfor %}
<input type="hidden" name="s" value="{{idQ}}" readonly>
the view:
def createQcm(request):
q=request.POST["choix"]
r=request.POST["s"]
rep = contenir(idQuestion=q,idQuiz=r)
rep.save()
return render(request,'myblog/subject.html')
How can I save them all?

Django, Getting a value from a POST

I have in my template:
This is passed by {{form}}
<form action="" method="POST">
Inicio: <input type="text" id="start">
<input type="submit" value="Sned" >
{% csrf_token %}
</form>
Then in the views.py
def test(request):
if request.method != 'POST':
context = {'form': 'by GET'}
return render(request, 'test.html', context)
else:
if 'start' in request.POST:
start = request.POST['start']
else:
start = False
context = {'form': start}
return render(request, 'test.html', context)
It seems that always return False
If I dont check the existance of the key I have this error:
MultiValueDictKeyError
And the erropage says : "'start'" (single plus double quotes)
id is intended for javascript and css purposes. For variables that are important on server side, you should use name tag.
<input type="text" id="start" name="start">
You need to add a name attribute in your input, so when you are getting the POST data it will be found.
<form action="" method="POST">
Inicio: <input type="text" id="start" name="start">
<input type="submit" value="Sned" >
{% csrf_token %}
</form>
Also I recommend you to do the following change in your view:
Replace
request.POST['start']
by:
request.POST.get('start')
So, if the field is not found, it will be reassigned whith a None value.
add name
<input type="text" name="start" id="start">

Django, form is_valid() is always false

I'm learning Django and have some troubles with forms. I try to create a simple form where I type a name and show it on another page. But is_valid() always returns false. Please, help me to find my error
forms.py
from django import forms
class OrderForm(forms.Form):
user=forms.CharField(max_length=100)
views.py
def order(request):
return render(request, 'myapp/order.html', {})
def contact(request):
username='not logged'
if request.method == 'POST' :
form=OrderForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
else:
username='not worked'
else:
form=OrderForm()
return render(request, 'myapp/contacts.html', {'username':username})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
<input type="text" name="username" placeholder="Name">
<button type="submit">Login</button>
</form>
contacts.html
You are : <strong>{{ username }}</strong>
Your form control has the name username in HTML, while your form's field is named user in Django. Thus, nothing is set in the form field.
Normally you'd put the form into the context and then render it either as {{ form }} or the like, or render each field, rather than build your own form controls. The docs show how: https://docs.djangoproject.com/en/1.10/topics/forms/#working-with-form-templates
views.py
from forms import OrderForm
def order(request):
form = OrderForm()
return render(request, 'myapp/order.html', {"form" : form})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
{{form.as_p}}
<button type="submit">Login</button>
</form>
At the time of rendering template {{form.as_p}} looks like
<p><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="100" required /></p>

Django check if checkbox is selected

I'm currently working on a fairly simple django project and could use some help. Its just a simple database query front end.
Currently I am stuck on refining the search using checkboxes, radio buttons etc
The issue I'm having is figuring out how to know when a checkbox (or multiple) is selected. My code so far is as such:
views.py
def search(request):
if 'q' in request.GET:
q = request.GET['q']
if not q:
error = True;
elif len(q) > 22:
error = True;
else:
sequence = Targets.objects.filter(gene__icontains=q)
request.session[key] = pickle.dumps(sequence.query)
return render(request, 'result.html', {'sequence' : sequence, 'query' : q, 'error' : False})
return render(request, 'search.html', {'error': True})
search.html
<p>This is a test site</p></center>
<hr>
<center>
{% if error == true %}
<p><font color="red">Please enter a valid search term</p>
{% endif %}
<form action="" method="get">
<input type="text" name="q">
<input type="submit" value="Search"><br>
</form>
<form action="" method="post">
<input type='radio' name='locationbox' id='l_box1'> Display Location
<input type='radio' name='displaybox' id='d_box2'> Display Direction
</form>
</center>
My current idea is that I check which checkboxes/radio buttons are selected and depending which are, the right data will be queried and displayed in a table.
So specifically:
How do I check if specific check-boxes are checked? and how do I pass this information onto views.py
Radio Buttons:
In the HTML for your radio buttons, you need all related radio inputs to share the same name, have a predefined "value" attribute, and optimally, have a surrounding label tag, like this:
<form action="" method="post">
<label for="l_box1"><input type="radio" name="display_type" value="locationbox" id="l_box1">Display Location</label>
<label for="d_box2"><input type="radio" name="display_type" value="displaybox" id="d_box2"> Display Direction</label>
</form>
Then in your view, you can look up which was selected by checking for the shared "name" attribute in the POST data. It's value will be the associated "value" attribute of the HTML input tag:
# views.py
def my_view(request):
...
if request.method == "POST":
display_type = request.POST.get("display_type", None)
if display_type in ["locationbox", "displaybox"]:
# Handle whichever was selected here
# But, this is not the best way to do it. See below...
That works, but it requires manual checks. It's better to create a Django form first. Then Django will do those checks for you:
forms.py:
from django import forms
DISPLAY_CHOICES = (
("locationbox", "Display Location"),
("displaybox", "Display Direction")
)
class MyForm(forms.Form):
display_type = forms.ChoiceField(widget=forms.RadioSelect, choices=DISPLAY_CHOICES)
your_template.html:
<form action="" method="post">
{# This will display the radio button HTML for you #}
{{ form.as_p }}
{# You'll need a submit button or similar here to actually send the form #}
</form>
views.py:
from .forms import MyForm
from django.shortcuts import render
def my_view(request):
...
form = MyForm(request.POST or None)
if request.method == "POST":
# Have Django validate the form for you
if form.is_valid():
# The "display_type" key is now guaranteed to exist and
# guaranteed to be "displaybox" or "locationbox"
display_type = request.POST["display_type"]
...
# This will display the blank form for a GET request
# or show the errors on a POSTed form that was invalid
return render(request, 'your_template.html', {'form': form})
Checkboxes:
Checkboxes work like this:
forms.py:
class MyForm(forms.Form):
# For BooleanFields, required=False means that Django's validation
# will accept a checked or unchecked value, while required=True
# will validate that the user MUST check the box.
something_truthy = forms.BooleanField(required=False)
views.py:
def my_view(request):
...
form = MyForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
...
if request.POST["something_truthy"]:
# Checkbox was checked
...
Further reading:
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#choicefield
https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#radioselect
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#booleanfield
In models :
class Tag:
published = BooleanField()
(...)
In the template:
{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value="" {% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
Assuming you are sending the form as a POST, the values of the selected checkboxes are in request.POST.getlist('tag').
For example :
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />
Say if 1,4 were checked,
check_values = request.POST.getlist('tag')
check_values will contain [1,4] (those values that were checked)
{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value=""
{% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />

Categories

Resources