djangodocs.org

654 sections in Django 4.2 Search all versions →

How-to How to create custom model fields Writing a field subclassUseful methods

To customize the form field used by ModelForm, you can override formfield(). The form field class can be specified via the form_class and choices_form_class arguments; the latter is used if the field has choices specified, the former otherwise.

Write a minimal form

Tutorial Writing your first Django app, part 4

Let’s update our poll detail template (“polls/detail.html”) from the last tutorial, so that the template contains an HTML <form> element: polls/templates/polls/detail.html A quick rundown: The above template displays a radio button for each question choice.

Write a minimal form

Tutorial Writing your first Django app, part 4

The above code checks for KeyError and redisplays the question form with an error message if choice isn’t given. After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse.

Write a minimal form

Tutorial Writing your first Django app, part 4

<ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a>

Reference The Forms API Outputting forms as HTML

Form.error_css_class Form.required_css_class It’s pretty common to style form rows and fields that are required or have errors. For example, you might want to present required form rows in bold and highlight errors in red.

Topic guide Working with forms More about Django Form classes

The distinction between Bound and unbound forms is important: An unbound form has no data associated with it. When rendered to the user, it will be empty or will contain default values.

Reference The Forms API

Form.fields You can access the fields of Form instance from its fields attribute: You can alter the field and BoundField of Form instance to change the way it is presented in the form: Beware not to alter the base_fields attribute …

Topic guide Creating forms from models Inline formsets

inlineformset_factory uses modelformset_factory and passes most of its arguments to modelformset_factory. This means you can use the widgets parameter in much the same way as passing it to modelformset_factory. See Specifying widgets to use in the form with widgets above.

label

Reference Form fields Core field arguments

Field.label The label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.