ChoiceField – Django Forms



ChoiceField – Django Forms

 

The ChoiceField in Django Forms is a powerful tool for selecting a choice from a list of pre-defined options. This feature is particularly useful for fields such as countries or states, where users must choose one option from a set of predefined choices.

The ChoiceField can be used to take text inputs from the user, and the default widget for this input is Select. The ChoiceField has one extra required argument, choices, which can be either an iterable of 2-tuples or a callable that returns such an iterable. By using this field, developers can streamline the process of collecting user input and reduce the likelihood of user input errors.

To use the ChoiceField, developers must create a form and map it to a URL in Django. The ChoiceField can be used to input small-sized strings in the database, such as state, country, city, or any other predefined option.

By default, the ChoiceField assumes that the value is required, so developers must set the required argument to False if the value is not required. The label argument can be used to specify a human-friendly label for this field, and the help_text argument allows developers to provide descriptive text for this field.

ChoiceField has one extra required argument :

  • choices :
    Either an iterable of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field.

Syntax

field_name = forms.ChoiceField(**options)

Django form ChoiceField Explanation

Illustration of ChoiceField using an Example. Consider a project named geeksforgeeks having an app named geeks.

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

from django import forms
# iterable
GEEKS_CHOICES =(
("1", "One"),
("2", "Two"),
("3", "Three"),
("4", "Four"),
("5", "Five"),
)
# creating a form 
class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices = GEEKS_CHOICES)

Add the geeks 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 render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of 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 are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.
Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.

<form method = "GET">
{{ form }}
<input type = "submit" value = "Submit">
</form>

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

from django.urls import path
# importing views from views..py
from .views import home_view
urlpatterns = [
path('', home_view ),
]

Let’s run the server and check what has actually happened, Run

Python manage.py runserver

django-forms-choicefield

Thus, an geeks_field ChoiceField is created by replacing “_” with ” “. It is a field to input choices of strings.

How to use ChoiceField ?

ChoiceField is used for input of small-sized strings in the database. One can input state, country, city, etc. Till now we have discussed how to implement ChoiceField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.
In views.py,

from django.shortcuts import render
from .forms import GeeksForm
# Create your views here.
def home_view(request):
context ={}
form = GeeksForm()
context['form']= form
if request.GET:
temp = request.GET['geeks_field']
print(temp)
return render(request, "home.html", context)

Now let’s try entering data into the field.

django-choicefield-forms-1

Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose.

django-choicefield-forms

Core Field Arguments

Examples of ChoiceField with Core Field Arguments

Let’s see how to use ChoiceField with some of the core field arguments, which can be passed while initializing the field object.

Required False

If we want to allow the user to leave the ChoiceField empty, we can set the required argument to False. The default value of the required argument is True.

class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices=GEEKS_CHOICES, required=False)

 

Label

The label argument can be used to specify a human-friendly label for the field. This label is displayed when the field is rendered in a form.

class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices=GEEKS_CHOICES, label="Choose a number")

 

Label Suffix

The label_suffix argument can be used to override the form’s label suffix on a per-field basis.

class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices=GEEKS_CHOICES, label_suffix=":")

 

Widget

The widget argument can be used to specify a widget class to use when rendering the field. For example, if we want to render the ChoiceField as radio buttons instead of a dropdown, we can use the RadioSelect widget.

class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices=GEEKS_CHOICES, widget=forms.RadioSelect)

 

Help Text

The help_text argument can be used to provide a description of the field, which is displayed next to the field when it is rendered.

class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices=GEEKS_CHOICES, help_text="Please choose a number")

 

Error Messages

The error_messages argument can be used to override the default error messages raised by the field. We can pass a dictionary with keys matching the error messages we want to override.

class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices=GEEKS_CHOICES, error_messages={'required': 'Please choose a number'})

 

Validators

The validators argument can be used to provide a list of validation functions for the field. We can pass a list of functions that take the value of the field as an argument and raise a ValidationError if the validation fails.

def validate_even(value):
if int(value) % 2 != 0:
raise forms.ValidationError("Please choose an even number")

class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices=GEEKS_CHOICES, validators=[validate_even])

 

Localize

The localize argument enables the localization of form data input, as well as the rendered output.

class GeeksForm(forms.Form):
geeks_field = forms.ChoiceField(choices=GEEKS_CHOICES, localize=True)

Last Updated on April 16, 2023 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs