Change language

MultipleChoiceField — Django Forms

MultipleChoiceField has one required argument:

  • Choices : — either an iteration of 2 tuples to use as a selection for that field, or a callable function that returns such an iteration.

Syntax

 field_name = forms.MultipleChoiceField ( ** options ) 

Django form MultipleChoiceField Explanation

MultipleChoiceField illustration with using an example. Consider a project named pythonengineering that has an application named geeks .

Refer to the following articles to check how to create a project and an app in Django.

Enter the following code into the forms.py file of the geeks application.

from django import forms

 

DEMO_CHOICES = (

( " 1 " , "Naveen" ),

( "2" , "Pranav" ),

( "3" , "Isha" ),

( "4 " , " Saloni " ),

)

class GeeksForm (form s.Form):

geeks_field = forms.MultipleChoiceField (choices = DEMO_CHOICES)

 

Add the geek app to INSTALLED_APPS

# Application definition

 

INSTALLED_APPS = [

’django.contrib.admin’ ,

  ’ django.contrib.auth’ ,

  ’django.contrib.contenttypes’ ,

’django.contrib.sessions’ ,

’django.contrib.messages’ ,

’django.contrib.staticfiles’ ,

’geeks’ ,

]

Now, to convert this form to a view, we need a view and a URL associated with that URL. Let’s first create a view in the views.py of the geeks app,

from django .shortcuts import render

from . forms import GeeksForm

 
# Create your views here.

def home_view (request):

context = {}

  context [ ’form’ ] = GeeksForm ()

return render (request, "home.html" , context)

Here we import this particular form from forms.py and instantiate it in the view so that it could be displayed in the template. 
Now, to initiate your Django form, you need to create a home.html where you can create things as you see fit. Let’s create a form in home.html .

" form method = "POST"

{% csrf_token%}

{{form.as_p}}

" input type = "submit" value = " Submit "

"/ form

Finally, the URL to map to this view in urls.py

from django.urls import path

 
# import views from views..py

from . views import home_view

 

urlpatterns = [

  path (’’, home_view),

]

Let’s start the server and check what’s on actually happened, Run

 Python manage.py runserver 

Thus, the geeks_field MultipleChoiceField is created by replacing "_" with "". This is a field for entering a selection from a list.

How to use a MultipleChoiceField?

MultipleChoiceField is used to enter a selection into the database. You can enter Gender, etc. So far we have discussed how to implement MultipleChoiceField, but how to use it in the view to execute the boolean part. To do some logic, we need to get the value entered in the field into a Python string instance. To get the Github code for a working MultipleChoiceField, click here .

.py,

from django.shortcuts import render

from . forms import GeeksForm

 
# Create your views here.

def home_view (request ):

context = {}

  form = GeeksForm (request.POST or None )

context [ ’form’ ] = form

if request.POST:

if form.is_valid ():

temp = form.cleaned_data.get ( " geeks_field " )

  print ( temp)

return render (request , "home.html" , context)

Let’s try to select the selection data now. 

This data can now be retrieved using the appropriate query dictionary. If the method is GET, the data will be available in request.GET, and if post, then request.POST , respectively. In the above example, we have a value in temp that we can use for any purpose. You can check that the data is converted to a Python list of the string instance in the geeks_field.

Basic Field Arguments

Basic Field Arguments — they are arguments given to each field to apply some kind of constraint or to convey a particular characteristic to a particular field. For example, adding the required = False argument to the MultipleChoiceField will allow the user to leave it blank. Each Field constructor takes at least these arguments. Some Field classes accept additional field-specific arguments, but you should always accept the following:

Field Options Description
required By default, each Field class assumes the value is required, so to make it not required you need to set required=False
label The label argument lets you specify the “ human-friendly ”label for this field. This is used when the Field is displayed in a Form.
label_suffix The label_suffix argument lets you override the form’s label_suffix on a per-field basis.
widget The widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information.
help_text The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods.
error_messages The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
validators The validators argument lets you provide a list of validation functions for this field.
localize The localize argument enables the localization of form data input, as well as the rendered output.
disabled The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users.

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically