Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

django
communitycreator

What is ChoiceField in Django Forms?

Njoku Ifeanyi Gerald

Django is an open-source, high-level Python web framework that encourages rapid development and clean, pragmatic design.

ChoiceField in Django Forms is a string field for selecting a particular choice out of a list of available choices. ChoiceField can be used in cases where there are a limited number of pre-defined options to select from, e.g., selecting a country from a list of countries or a day from among the seven days of the week.

ChoiceField is similar to an option field in web pages, where someone can select an option of their choice from a list of options.

ChoiceField uses an iterable of a 2-tuple to add as choices.

Code

A basic implementation of a ChoiceField is shown below:

class FRUIT(forms.Form):
  CHOICES = (
      (1, 'Orange'),
      (2, 'Mango'),
      (3, 'Strawberries'),
      (4, 'Grapes'),
      
  )
  name = forms.CharField()
  category = forms.ChoiceField(choices=CHOICES)
example.py

In the code above, the fruit names are the choices that can be chosen from.

A complete demonstration of how the choices would be part of the application is provided below.

Let’s start with installation:

pip install pipenv
pipenv shell
pipenv install django

Then:

django-admin startproject DjangoChoiceField ./
python manage.py startapp codebase
python manage.py migrate
python manage.py runserver

Next, add the code below to settings.py.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'codebase'
]
settings.py

In the codebase app folder, go to forms.py and use ChoiceField to make the options for the form.

from django import forms

  
#The choices to choose from
DEPARTMENTS =(
    ( "BCH","biochemistry"),
    ( "EE","electrical engineering"),
    ( "BTC", "biotechnology"),
    ("MCB","microbiology"),
    ( "BIO","biology"),
    ( "CE", "chemical engineering"),
    ( "OPT", "Optometry"),
    ( "SE", "software engineering"),
    ( "PUT", "public Health"),
    ("STA", "statistics" ),
    
)
  
# creating a form 
class ChoiceForm(forms.Form):
    departments  = forms.ChoiceField(choices = DEPARTMENTS)
forms.py

In views.py, a view for the web page itself is created as follows.

from django.shortcuts import render
from .forms import  ChoiceForm
  
# Create your views here.
def home(request):
    form = ChoiceForm()
    context = {
        'form': form
    }
    return render( request,"app/home.html", context)
views.py

In the codebase app, create a folder and name it “templates.” Inside the “templates” folder, create another folder and name it “app.” Then, inside the “app” folder, create the home.html file, which displays a web page that contains the form and a button to submit it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <br>
    Different FUTO departments
    <br><br>
    <form method = "GET">
        {{ form }}
        <input type = "submit" value = "Submit">
    </form>
</body>
</html>
home.html

In the “DjangoChoiceField” folder, the following is added to urls.py.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    # including the codebase urls.py file
    path('', include('codebase.urls'))
]

In the codebase folder, create a file and name it urls.py with the content below to route the web pages across the application.

from django.urls import path
#import the home function from the views.py file
from .views import home


urlpatterns = [
    #creating a route
    path('', home, name='home'),
]
urls.py

Finally, to run the application and interact with the form, run the following commands:

python manage.py makemigrations

python manage.py migrate
python manage.py runserver

The result can be viewed on the localhost (http://127.0.0.1:8000) to access the app.

RELATED TAGS

django
communitycreator

CONTRIBUTOR

Njoku Ifeanyi Gerald
RELATED COURSES

View all Courses

Keep Exploring