Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a checkbox in a django form

I've a settings page where users can select if they want to receive a newsletter or not.

I want a checkbox for this, and I want that Django select it if 'newsletter' is true in database. How can I implement in Django?

like image 570
Fred Collins Avatar asked Jun 01 '11 01:06

Fred Collins


People also ask

How to add checkbox in Django form?

You can just add required=False on your forms. BooleanField() args.

What is widget in Django?

A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <! DOCTYPE html> .

How do I create a form in Django?

Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on.


2 Answers

models.py:

class Settings(models.Model):     receive_newsletter = models.BooleanField()     # ... 

forms.py:

class SettingsForm(forms.ModelForm):     receive_newsletter = forms.BooleanField()      class Meta:         model = Settings 

And if you want to automatically set receive_newsletter to True according to some criteria in your application, you account for that in the forms __init__:

class SettingsForm(forms.ModelForm):      receive_newsletter = forms.BooleanField()      def __init__(self):         if check_something():             self.fields['receive_newsletter'].initial  = True      class Meta:         model = Settings 

The boolean form field uses a CheckboxInput widget by default.

like image 63
Timmy O'Mahony Avatar answered Oct 10 '22 03:10

Timmy O'Mahony


You use a CheckBoxInput widget on your form:

https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxInput

If you're directly using ModelForms, you just want to use a BooleanField in your model.

https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield

like image 44
Paul McMillan Avatar answered Oct 10 '22 03:10

Paul McMillan