🎓 A1Learner
🔍
0 of 50 lessons completed

Django Form Fields

Form fields name the values a form collects. Each field type takes its own kind of value.

Three field types

Each field takes its own kind of value. Name takes text, age takes a number, and email takes an address.

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=50)
    age = forms.IntegerField()
    email = forms.EmailField()

List the three fields

Fields holds the form fields by name. The list shows all three names.

form = ContactForm({"name": "Sana", "age": "30", "email": "sana@example.com"})
print(list(form.fields))

Read the typed number

The form keeps the typed age under its field name. The print shows 30.

print(form["age"].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 ContactForm(forms.Form):
    name = forms.CharField(max_length=50)
    age = forms.IntegerField()
    email = forms.EmailField()

form = ContactForm({"name": "Sana", "age": "30", "email": "sana@example.com"})
print(list(form.fields))
print(form["age"].value())
print(form["email"].value())

Key points

  • Use forms.CharField for short typed text.
  • Use forms.IntegerField for whole numbers.
  • Use forms.EmailField for email addresses.
  • Each field can cap its length, like max_length=50.
  • Fields live in the form class, one line each.

In this example, the setup lines configure Django. ContactForm holds three fields, one per typed value. CharField takes the short name text, and max_length caps it at 50 letters. IntegerField takes the whole number age. EmailField takes the email address. The form is made with a dict of typed values. The first print lists the three field names. The next prints read the typed age and the typed email.

Note

A field name becomes the key in the typed values.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which field takes a whole number?