Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 77 ยท Forms

Django Form Field Reference

A tour of Django's built-in form fields and their arguments (strip, empty_value, typed choices, FilePathField, RegexField, IP and duration fields) plus every way to render a form.

Django Forms introduced CharField, IntegerField and friends. Django ships with many more field classes, and most of the surprises live in their arguments: what does empty_value do, why does a ChoiceField always return a string, how do you accept only IPv4 addresses, and how can a form offer a list of files on the server? This lesson walks through the fields you meet less often, with output from the real library, and then shows the ways to turn a form into HTML.

Every field accepts the common arguments you already know: required, label, initial, help_text, widget, validators, error_messages and disabled. The sections below add what is specific to each field.

Text and number fields

CharField has two arguments that decide what "blank" means:

  • strip (default True) removes leading and trailing whitespace before validation, so a value of only spaces counts as empty and fails required=True. Pass strip=False for text where spaces matter, such as a password or a code.
  • empty_value is the Python value stored in cleaned_data when the field is left empty. It defaults to the empty string "". Use None when "no value" should be different from "empty text", for example when the form feeds a nullable database column.

empty_value goes through the field's validators like any other value. EmailField(required=False, empty_value="n/a") rejects a blank submission because "n/a" is not an email address. Stick to None or "" unless the replacement is itself valid.

EmailField and SlugField build on CharField and inherit both arguments. SlugField accepts only letters, numbers, underscores and hyphens, and allow_unicode=True also allows non-ASCII letters. DecimalField takes max_digits (all digits) and decimal_places (digits after the point), plus max_value and min_value; it returns a Decimal, never a float. DurationField accepts text such as 90 (seconds), 2 12:00 (days, then hours and minutes) or 1 02:03:04.5 and returns a timedelta.

Python Text, number and duration fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three spaces became None thanks to strip plus empty_value=None, the bio kept its spaces because of strip=False, and 90 was read as ninety seconds.

Choice fields and typed choices

A ChoiceField receives a string from the browser and gives you the same string back, even when the choices look like numbers. That is rarely what you want for numeric codes. TypedChoiceField adds two arguments:

  • coerce is a callable (int, float, or your own function) that converts the valid string into the type you need.
  • empty_value is what you get when the user chose the empty option.

TypedMultipleChoiceField does the same for a list of selections (a <select multiple> or a group of checkboxes). NullBooleanField supports three states, yes, no and unknown, which a plain BooleanField cannot express because it merges "unchecked" and "not answered" into False. It renders as a select box with Unknown, Yes and No.

Python Typed choice fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The valid choice "2" came back as the integer 2, ["1", "3"] came back as [1, 3], and the unknown value became None. A value outside the choices is rejected before coerce ever runs.

FilePathField, GenericIPAddressField and RegexField

FilePathField builds its choices from a directory on the server. The arguments control what is listed:

Argument Meaning
path Absolute directory to list (required)
match Regular expression applied to the file name; only matching names are listed
recursive Also list sub-directories (default False)
allow_files List files (default True)
allow_folders List folders (default False)

GenericIPAddressField validates IP addresses. protocol is "both" (default), "IPv4" or "IPv6". With unpack_ipv4=True, an IPv4-mapped IPv6 address such as ::ffff:192.0.2.1 is converted to plain 192.0.2.1, which is handy when you compare addresses or store them in a column. RegexField takes a regex (string or compiled pattern) and optionally strip; its failure message has the code invalid, so you can replace it through error_messages.

Python Paths, IP addresses and patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The match pattern is tested against the file name only, while recursive=True adds the sub-folder (/archive/old.csv) to the label. The choices are read when the field is created, so a field declared at class level lists the directory once, when the module loads. Build it in __init__ if the folder changes while the server runs.

Rendering a form

A form object knows how to render itself. There are four built-in shortcuts and one manual approach.

Call in a template Output
{{ form.as_div }} One <div> per field (what {{ form }} uses by default since Django 5.0)
{{ form.as_p }} One <p> per field
{{ form.as_ul }} One <li> per field; you add the surrounding <ul>
{{ form.as_table }} One <tr> per field; you add the surrounding <table>

All of them render labels, widgets, help text and errors, with matching id and for attributes. They never output the <form> tag, the CSRF token or the submit button, and as_ul and as_table leave out the wrapping <ul> and <table>, because a form often shares them with other content.

For full control, loop over the fields and place each part yourself. A bound field exposes label, id_for_label, html_name, help_text, errors, value and field, and as_widget(attrs=...) renders just the input with extra attributes. This is the usual way to apply CSS framework classes without writing a custom widget.

Python Rendering a form in different ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A typical hand-written template looks like this (read-only, it needs a view to run):

DJANGO
<form method="post">
  {% csrf_token %}
  {% for field in form %}
    <div class="mb-3">
      {{ field.label_tag }}
      {{ field }}
      {% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}
      {% for error in field.errors %}<p class="error">{{ error }}</p>{% endfor %}
    </div>
  {% endfor %}
  <button type="submit">Send</button>
</form>

If every field gets the same CSS class, set it once in the form's __init__ by looping over self.fields.values() and updating field.widget.attrs, rather than repeating it in every template.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user types only spaces into a required CharField. What happens by default?

    CharField strips whitespace by default (strip=True), so the value becomes empty and a required field reports an error. Use strip=False to keep spaces.
  2. 2. Why use TypedChoiceField(coerce=int) instead of ChoiceField?

    Browsers send text. ChoiceField gives that text back, while TypedChoiceField runs coerce on the validated value so cleaned_data holds the right type.
  3. 3. What does GenericIPAddressField(unpack_ipv4=True) do with ::ffff:192.0.2.1?

    unpack_ipv4 turns IPv4-mapped IPv6 addresses into plain IPv4 strings. It only applies when the protocol allows both.
  4. 4. Which template call renders each field in a paragraph?

    as_p wraps every field in a <p>. as_ul and as_table need you to add the surrounding <ul> or <table>.

Summary

  • CharField strips whitespace by default; empty_value decides what an empty submission becomes (keep it valid for the field's validators).
  • DecimalField limits digits with max_digits and decimal_places; DurationField returns a timedelta.
  • TypedChoiceField and TypedMultipleChoiceField convert choices with coerce; NullBooleanField keeps "unknown" separate from "no".
  • FilePathField lists server files using path, match, recursive, allow_files and allow_folders.
  • GenericIPAddressField takes a protocol and can unpack IPv4-mapped addresses; RegexField validates against a pattern.
  • Render with as_div, as_p, as_ul, as_table, or loop over fields and use as_widget(attrs=...).

Next, learn how to write your own rules in form validation.