π 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:
ChoiceFieldwithSelectwidget for dropdownBooleanFieldfor checkboxChoiceFieldwithRadioSelectwidget 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
nameis a text fieldcourseis a dropdownhostelis a checkboxgenderis 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
- User opens the form page
- Fills text field, dropdown, checkbox, and radio buttons
- Form is submitted using POST
- Django validates the form
- Submitted values are extracted using
cleaned_data - 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
- Add one more dropdown for semester
- Add multiple checkboxes for hobbies
- Add radio buttons for mode of study (Regular/Distance)
- Show βYesβ or βNoβ instead of True/False for hostel
- 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
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
