Django

Create a Form Containing Dropdown and Radio Button Inputs

πŸ“Œ Introduction

In Django forms, we can create different input controls such as:

  • Dropdown for selecting one option from many
  • Checkbox for true/false choice
  • Radio buttons for selecting one option from a group

In this program, we will create a form that contains:

  • a dropdown for course selection
  • a checkbox for hostel requirement
  • radio buttons for gender

After submission, the selected values will be displayed on the same page.


🎯 Program Statement

πŸ‘‰ Create a form containing dropdown, checkbox, and radio button inputs.


🧠 Concept

This program uses:

  • ChoiceField with Select widget for dropdown
  • BooleanField for checkbox
  • ChoiceField with RadioSelect widget for radio buttons

βš™οΈ Step 1: Create Form

πŸ“ File: forms.py

πŸ”Ή Path:

myproject/myapp/forms.py

πŸ”Ή Code:

from django import forms

class StudentInputForm(forms.Form):
COURSE_CHOICES = [
('BCA', 'BCA'),
('MCA', 'MCA'),
('BTech', 'BTech'),
]

GENDER_CHOICES = [
('Male', 'Male'),
('Female', 'Female'),
('Other', 'Other'),
]

name = forms.CharField(label='Enter Name', max_length=100)

course = forms.ChoiceField(
label='Select Course',
choices=COURSE_CHOICES
)

hostel = forms.BooleanField(
label='Require Hostel',
required=False
)

gender = forms.ChoiceField(
label='Select Gender',
choices=GENDER_CHOICES,
widget=forms.RadioSelect
)

🧠 Explanation

  • name is a text field
  • course is a dropdown
  • hostel is a checkbox
  • gender is shown as radio buttons

required=False is used for checkbox because the user may leave it unchecked.


βš™οΈ Step 2: Create View

πŸ“ File: views.py

πŸ”Ή Path:

myproject/myapp/views.py

πŸ”Ή Code:

from django.shortcuts import render
from .forms import StudentInputForm

def student_inputs(request):
submitted_data = None

if request.method == 'POST':
form = StudentInputForm(request.POST)
if form.is_valid():
submitted_data = {
'name': form.cleaned_data['name'],
'course': form.cleaned_data['course'],
'hostel': form.cleaned_data['hostel'],
'gender': form.cleaned_data['gender'],
}
else:
form = StudentInputForm()

return render(request, 'student_inputs.html', {
'form': form,
'data': submitted_data
})

🧠 Explanation

  • Form is displayed when page loads
  • On submission, Django validates all input
  • Submitted values are stored in a dictionary
  • Dictionary is displayed in the template

βš™οΈ Step 3: URL Mapping

πŸ“ File: urls.py

πŸ”Ή Path:

myproject/myproject/urls.py

πŸ”Ή Code:

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('student-inputs/', views.student_inputs, name='student_inputs'),
]

βš™οΈ Step 4: Create Template

πŸ“ File: student_inputs.html

πŸ”Ή Path:

myproject/templates/student_inputs.html

πŸ”Ή Code:

<!DOCTYPE html>
<html>
<head>
<title>Student Input Form</title>
</head>
<body>

<h1>Student Input Form</h1>

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

<hr>

{% if data %}
<h2>Submitted Details</h2>
<p><strong>Name:</strong> {{ data.name }}</p>
<p><strong>Course:</strong> {{ data.course }}</p>
<p><strong>Hostel Required:</strong> {{ data.hostel }}</p>
<p><strong>Gender:</strong> {{ data.gender }}</p>
{% endif %}

</body>
</html>

🧠 Explanation

  • {{ form.as_p }} automatically renders all controls
  • Dropdown, checkbox, and radio buttons appear according to field type and widget
  • Submitted values are displayed below the form

βš™οΈ Step 5: Run Server

python manage.py runserver

🌐 Step 6: Output

Open:

πŸ‘‰ http://127.0.0.1:8000/student-inputs/

βœ… Example Input:

  • Name: Juhi
  • Course: MCA
  • Hostel: checked
  • Gender: Female

βœ… Output:

Submitted Details
Name: Juhi
Course: MCA
Hostel Required: True
Gender: Female

If hostel is not checked, output will be:

Hostel Required: False

🧠 How It Works

  1. User opens the form page
  2. Fills text field, dropdown, checkbox, and radio buttons
  3. Form is submitted using POST
  4. Django validates the form
  5. Submitted values are extracted using cleaned_data
  6. Template displays the values

πŸ”₯ Key Concepts

Dropdown Field

forms.ChoiceField(choices=COURSE_CHOICES)

Used to select one option from a list.


Checkbox Field

forms.BooleanField(required=False)

Used for yes/no or true/false input.


Radio Buttons

forms.ChoiceField(widget=forms.RadioSelect)

Used to select one option from a group shown as radio buttons.


Choices

COURSE_CHOICES = [
('BCA', 'BCA'),
('MCA', 'MCA'),
]

Each choice has:

  • stored value
  • displayed label

⚠️ Common Errors

❌ Checkbox made compulsory by mistake

If you do not use required=False, Django may force the user to check it.


❌ Radio buttons not showing

Make sure this widget is used:

widget=forms.RadioSelect

❌ Dropdown not showing choices

Ensure choices= is added properly.


❌ Forgot {% csrf_token %}

POST form will fail due to CSRF protection.


❌ Form imported incorrectly

Use:

from .forms import StudentInputForm

πŸ§ͺ Practice Questions

  1. Add one more dropdown for semester
  2. Add multiple checkboxes for hobbies
  3. Add radio buttons for mode of study (Regular/Distance)
  4. Show β€œYes” or β€œNo” instead of True/False for hostel
  5. Add default selected course

🎀 Viva Questions & Answers

1. What is a dropdown in Django forms?

A dropdown is created using ChoiceField. It allows the user to select one option from a list of predefined values.

2. What is the use of choices in Django forms?

choices defines the list of options shown in dropdowns or radio buttons. Each option has a stored value and a displayed label.

3. What is a checkbox field in Django?

A checkbox field is usually created using BooleanField. It is used for yes/no or true/false type input.

4. Why is required=False used with checkbox?

Because a checkbox may be left unchecked. If required=False is not used, Django may treat it as mandatory.

5. How are radio buttons created in Django forms?

Radio buttons are created using ChoiceField with widget=forms.RadioSelect. This displays all choices as selectable radio options.

6. What is the difference between dropdown and radio button?

Both allow single selection, but dropdown shows options in a list, while radio buttons show all options openly on the page.

7. What value does a checkbox return after submission?

A checkbox returns True if checked and False if unchecked.

8. Why do we use forms.py for such inputs?

forms.py provides a clean and structured way to define different form controls and validations.

9. Can we use multiple dropdowns and radio buttons in one form?

Yes, Django forms support any number of fields and input types in the same form.


πŸ‘‰ Next Post: Implement Custom Validation using clean() Method in forms.py
πŸ‘‰ Back to List: Django Programs (60 Questions with Solutions)


Further Reading

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

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