0
0
Djangoframework~5 mins

Form fields and widgets in Django

Choose your learning style9 modes available
Introduction

Form fields let users enter data. Widgets show how these fields look on the page.

You want to collect user input like names or emails.
You need to display a dropdown list for users to pick an option.
You want to show a checkbox for yes/no questions.
You want to customize how a form input looks or behaves.
You want to validate user input before saving it.
Syntax
Django
from django import forms

class MyForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'my-class'}))
    age = forms.IntegerField(widget=forms.NumberInput())
    agree = forms.BooleanField(widget=forms.CheckboxInput())

Each form field has a type like CharField or IntegerField.

Widgets control the HTML input element shown for that field.

Examples
Simple text input for a name.
Django
name = forms.CharField(widget=forms.TextInput())
Email input that checks for valid email format.
Django
email = forms.EmailField(widget=forms.EmailInput())
Text input customized to show a color picker.
Django
color = forms.CharField(widget=forms.TextInput(attrs={'type': 'color'}))
Checkbox for yes/no subscription choice.
Django
subscribe = forms.BooleanField(widget=forms.CheckboxInput())
Sample Program

This form collects a name, email, message, and a subscription checkbox. Widgets customize placeholders and input types.

Django
from django import forms

class ContactForm(forms.Form):
    full_name = forms.CharField(label='Full Name', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Your full name'}))
    email = forms.EmailField(label='Email Address', widget=forms.EmailInput(attrs={'placeholder': 'you@example.com'}))
    message = forms.CharField(label='Message', widget=forms.Textarea(attrs={'rows': 4, 'cols': 40}))
    subscribe = forms.BooleanField(label='Subscribe to newsletter', required=False, widget=forms.CheckboxInput())
OutputSuccess
Important Notes

Widgets can be customized with HTML attributes using attrs.

BooleanField uses CheckboxInput by default for yes/no choices.

Always set required=False for optional fields like checkboxes.

Summary

Form fields define what data users enter.

Widgets control how the input looks and behaves.

You can customize widgets with HTML attributes for better user experience.