Your First Django Form
A Django form is a class that describes fields for typed input. Each field names one value the reader types.
Write the form class
The class extends forms.Form. It holds one field named name.
from django import forms
class NameForm(forms.Form):
name = forms.CharField(max_length=50)List the fields
Fields holds the form fields by name. The list shows one name.
form = NameForm({"name": "Sana"})
print(list(form.fields))Read the typed value
The form keeps the typed value under its field name. The print shows Sana.
print(form["name"].value())Example
import django
from django.conf import settings
settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()
from django import forms
class NameForm(forms.Form):
name = forms.CharField(max_length=50)
form = NameForm({"name": "Sana"})
print(list(form.fields))
print(form["name"].value())
Key points
- A form class extends forms.Form.
- Each field in the class names one typed value.
- Use forms.CharField for short typed text.
- Make a form with the class, like NameForm().
- Give the form a dict of typed values, like NameForm({"name": "Sana"}).
In this example, the setup lines configure Django. NameForm extends forms.Form, and it holds one field named name. CharField takes short typed text, and max_length caps it at 50 letters. The form is made with a dict of typed values. The first print lists the field names. The second print reads the typed value under name.
Note
A form with data is bound, and a form with no data is unbound.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does forms.CharField describe?