Django BooleanField always checked even when value is false - python

I have a BooleanField in a standard Django Form defined as:
my_boolean_field = BooleanField(initial=True)
when I render my form with initial data, and my_boolean_field is set to an initial value of False, when the form renders it is still checked despite the fact that the value is false as the html shows:
<p><label for="id_2">my_boolean_field</label>:
<input checked="checked"
type="checkbox"
name="2"
value="False"
id="id_2" />
</p>
Has anyone else experienced this, or knows how to fix it so that when the initial data/input value is false then the checkbox is not checked?
UPDATE: Even if I remove the initial=True argument from the BooleanField the same thing happens.

Firstly, you can't have required=False on a BooleanField, use NullBooleanField instead:
https://docs.djangoproject.com/en/dev/ref/models/fields/#booleanfield
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.NullBooleanField
let me know what the HTML output of the new widget is once you've done this?
EDIT
I assumed that this is a ModelForm. Is this a regular django.forms.Form?
EDIT 2
My test form:
from django import forms
class MyForm(forms.Form) :
"""The test form"""
my_boolean_field = forms.BooleanField(initial=True)
My template:
<div>
{{ form.my_boolean_field.label_tag }}
{{ form.my_boolean_field }}
{{ form.my_boolean_field.errors }}
</div>
This is what I get for output when I view page source. EDITED
<div>
<label for="id_my_boolean_field">My boolean field</label>
<input type="checkbox" name="my_boolean_field" id="id_my_boolean_field" />
</div>
My View NEW
form = MyForm(initial={'my_boolean_field':False})
What you are showing and what I'm seeing aren't matching up. paste your full form, view and template please?
EDIT 3
I only see output like this:
<div>
<label for="id_my_boolean_field">My boolean field</label>
<input checked="checked" type="checkbox" name="my_boolean_field" value="False" id="id_my_boolean_field" />
</div>
when I put False in quotes:
form = FormLogin(initial={'my_boolean_field':"False"})

I'm posting this answer because I had the same problem and Francis's answer didn't help me.
I eventually found the solution was to re-run manage.py syncdb. My fields had previously been IntegerField and I had converted them to BooleanField. BooleanField read the presence of value="0" in the database as being initialized and checked. This is regardless of what your model says. You want to see:
<input checked="checked" id="id_cost_track_destruction" name="cost_track_destruction" type="checkbox">
when you inspect an element. Since this bug shows up in the Django Admin panel, it has nothing to do with your forms.py.
This is purely a model and database issue. Try regenerating your database if you've changed your models.py field types.

For those who are using ModelForms, this is what worked for me:
password_required = forms.CheckboxInput(attrs={'checked' : ''})
This correctly generates the checkbox with it unchecked.

Related

Transferring front end data from HTML checkboxes to backend django in forms.py/views.py/urls.py

I have a bunch of checkboxes on my HTML page and want to store whether a checkbox was ticked or not in backend django. My current HTML code is:
<input type="checkbox" name="activism" value="Yes">Activism & advocacy
I don't know how to modify my forms.py/urls.py/views.py to store whether a particular checkbox was ticked or not. Thank you very much.
There you are, it's not the best way to. Since you are new to django, this will work. Alongside you're learning, take the django documentation as guide
<form action='url' method='post'> {% csrf_token %}
<input type="checkbox" name="activism" value="Yes">Activism & advocacy
<input type='submit' value="submit" />
</form>
python view
def viewName(request):
if request.method == 'POST':
# You have access to data inside request.POST
activism = request.POST.get('activism')
if activism:
pass # Activism is checked

How to manually make field in HTML? Django

in forms.py
class PlaceOrder(forms.ModelForm):
class Meta:
model = Order
fields = ["Product_ID","HowMany","DateSubmit",]
to call a form i usually use
{{ Form }}
that will render the form automatically
but is it possible to make it manually?
for example i want the form to be exactly like this
<input id="Product_ID" type="hidden" value="{{ Product.PId }}" >
<input id="HowMany" type="text">
<input id="DateSubmit" type="hidden" value="{{ date }}" >
i have tried wrapping them in
{% for field in form %}
but it gave the wrong output
Sorry if this is confusing
but i don't really know how to explain it,
i am still new to Django
You should be able to access individual fields in the form using something like
{{Form.Product_ID}}
which will give you the Product_ID field widget.
Now if you want to access the already pre-filled data you should be able to do so with
{{Form.Product_ID.label}}
or
{{Form.Product_ID.value}}
Also check:
https://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields

Flask-Bootstrap, flask-wtf, adding class to submit button

I'm using a flask-wtf submit button as follows:
{{ wtf.form_field(form.submit, button_map={'submit': 'primary'}) }}
I want to add a class to the submit button but I can not find anything about that,
I'm pretty new with this but this http://pythonhosted.org/Flask-Bootstrap/basic-usage.html#templates did not helped me a lot.
Anything to recommend?
It's super-easy, usually, so unless Flask-Bootstrap does something odd you can just tell it what you want the class to be:
{{ wtf.form_field(form.submit, class="something", button_map={'submit': 'primary'}) }}
Generally, anything you pass to the rendering function that isn't recognised will be added as a parameter to the html, so you can do things like:
{{ wtf.form_field(form.submit, cats="mew") }}
And your resulting html field would be something like <input cats="mew" id="name" name="name" type="text" value="">

flask-wtforms field required

how i can add tag required on this flask code :
{{ form.youtube_href(type='url', class='form-control') }}
actual output is :
<input class="form-control" id="youtube_href" name="youtube_href" value="" type="url">
need this output bat give error :
<input class="form-control" id="youtube_href" name="youtube_href" value="" type="url" required>
im tried this bat give error :
{{ form.youtube_href(type='url', class='form-control', 'required') }}
As of WTForms 2.2 (June 2nd, 2018), fields now render the required attribute if they have a validator that sets the required flag, such as DataRequired and InputRequired. If for some reason you don't want to render the attribute, you can pass required=False. Or if you want to disable all browser validation, you can set the novalidate attribute in the form tag. In general you should prefer to leave browser validation enabled, because it prevents a request/response for simple validation, which is desirable.
You are passing a positional argument after keyword arguments, which is a syntax error. Instead, pass required=True, which will set a bare attribute on the tag. Check the flags on a field to see if a Required validator was set: field.flags.required is a boolean. Create a URLField rather than passing the type manually.
from flask_wtf import Form
from wtforms.fields.html5 import URLField
from wtforms.validators import InputRequired
class MyForm(Form):
youtube_href = URLField(validators=[InputRequired()])
form = MyForm()
print(form.youtube_href(required=form.youtube_href.flags.required))
# <input id="youtube_href" name="youtube_href" required type="url" value="">
To those who simply want to add the required attribute to their html input, this can be accomplished by following the comment mentioned by Raja Simon above. Simply call your field name in your template with required='required' Example:
<form>
...
{{myform.my_name_field(required='required')}}
{{myform.my_email_field(required='required')}}
...
</form>
The Above code will result in fields like so:
<input id="my_name_field" name="my_name_field" required="required" type="text" value="">

Trouble posting un-checked checkbox value in django

I am finding trouble in posting the state of a checkbox in a Django form (Django v1.2).
Here's the field in my model:
subscribe = models.BooleanField(default=False, verbose_name="Subscribe")
In the relevant template file:
{{ form.subscribe }}
This renders the checkbox as un-checked initially. But when I post the form (without touching anything else), django sends u'subscribe': [u'on'] in request.POST. That is, the response always contains u'subscribe': [u'on'] irrespective of whether the checkbox is checked or not.
When the checkbox is not checked, the <input> tag in template is rendered as
<input type="checkbox" name="subscribe" id="id_subscribe" />
And, when the checkbox is checked, it is rendered as
<input type="checkbox" name="subscribe" id="id_subscribe" checked="checked" />
Am I missing anything here?
Your browser is what posts the value as 'on'. This is normal behavior for checkbox inputs without value="blah" attribute set. If it is always posting as 'on' even when the checkbox isn't checked then perhaps there is something on the browser side that is setting this.

Categories

Resources