Checkbox checking

320 views
Skip to first unread message

Jon Underwood

unread,
Aug 1, 2012, 7:37:12 AM8/1/12
to django...@googlegroups.com
Hi,

My checkboxes are giving me grief.

I want to make it required for the user to check a checkbox before being allowed to submit a forms.

I'm using model forms so the checkbox is defined as a models.BooleanField in my models.py. I have included blank=False, though this should be the default.

In the admin the checkboxes aren't required to be checked. When displaying the form in a template I can set required="True" as follows: <input type="checkbox" required="True" check_test="True" name="involved" id="id_involved"/>

This works in most browsers, though not Safari for some reason.

Is there a better method? I've messed around with this for ages!

Thank you in advance.

Jon

Carlos Palol

unread,
Aug 1, 2012, 11:35:48 AM8/1/12
to django...@googlegroups.com
It seems in this particular case you don't need the boolean field in the model. As the behaviour you want has to do only with the form, you just have to add an additional required checkbox in this model form.

class MyModelForm(forms.ModelForm):
involved = forms.BooleanField(required=True)
class Meta:
model = MyModel 

cheers

Bill Freeman

unread,
Aug 1, 2012, 12:02:56 PM8/1/12
to django...@googlegroups.com
I'm going to assume that we're talking about a single checkbox (an "I
agree to the terms" checkbox).

First, remember that unchecked is not the same as "blank", it is
"false", so "blank=False" is subject to interpretation.

There are two places where you might insist that the box be checked:
in the browser; and in the form processing. You *must* provide at
least the latter, since the first depends on JavaScript (since, as
you've discovered, the required attribute of a checkbox input doesn't
always work across browsers), which is disable-able and otherwise
circumventable.

The js approach is to disable the submit button on load (stays enabled
if js is disabled or the page is otherwise broken) and attach an on
change handler to the checkbox that enables or disables the submit
button based on whether the checkbox is now checked or not.

But the mandatory part is to add a validator to the field (see
https://docs.djangoproject.com/en/1.4/ref/forms/validation/ ) that
fails with a suitable error message if the checkbox field value is
False.
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/4bBr_gr_Z44J.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
Reply all
Reply to author
Forward
0 new messages