djangodocs.org

706 sections in Django 6.0 Search all versions →

Model form Meta API

Reference Model forms

classModelFormOptions[source] The _meta API is used to build forms that reflect a Django model. It is accessible through the _meta attribute of each model form, and is an django.forms.models.ModelFormOptions instance.

The form rendering API

Reference

Django’s form widgets are rendered using Django’s template engines system. The form rendering process can be customized at several levels: Widgets can specify custom template names. Forms and widgets can specify custom renderer classes.

Reference The form rendering API

Form templates receive a context from Form.get_context(). By default, forms receive a dictionary with the following values: form: The bound form. fields: All bound fields, except the hidden fields. hidden_fields: All hidden bound fields.

Reusable form templates

Topic guide Working with forms Working with form templates

The HTML output when rendering a form is itself generated via a template. You can control this by creating an appropriate template file and setting a custom FORM_RENDERER to use that form_template_name site-wide.

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.

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.