Creating a Form Class
Defining a Form Class
Every field you declare as a class attribute becomes one input on the rendered form, in the order you declare them.
Note: Field order in the class matches the order fields render on the page.
Example: Defining a Form Class
Every field you declare as a class attribute becomes one input on the rendered form, in the order you declare them.
from django import forms
class SignupForm(forms.Form):
username = forms.CharField(max_length=50)
age = forms.IntegerField()
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Required vs Optional Fields
Fields are required by default; pass required=False to make a field optional.
Example: Required vs Optional Fields
Fields are required by default; pass required=False to make a field optional.
class SignupForm(forms.Form):
username = forms.CharField(max_length=50)
bio = forms.CharField(required=False)
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Setting a Default Label
Django auto-generates a label from the field name, but you can override it with the label argument.
Example: Setting a Default Label
Django auto-generates a label from the field name, but you can override it with the label argument.
class SignupForm(forms.Form):
username = forms.CharField(max_length=50, label='Choose a username')
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
- Naming form fields differently from how the view later reads them from cleaned_data.
- Forgetting to import 'from django import forms' before subclassing forms.Form.
- Putting form classes inside views.py instead of a separate forms.py, making the app harder to navigate.
- A form class subclasses forms.Form and declares one attribute per field.
- Each field type (CharField, EmailField, IntegerField) enforces its own validation rules automatically.
- Form classes belong in forms.py, imported into views.py where they're used.
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: