The form rendering API
The form rendering process can be customized at several levels:
- Forms and widgets can specify custom renderer classes.
- A widget's template can be overridden by a project. (Reusable applicationstypically shouldn't override built-in templates because they might conflictwith a project's custom templates.)
The rendering of form templates is controlled by a customizable renderer class.A custom renderer can be specified by updating the setting. It defaults to'
'
.
You can also provide a custom renderer by setting theForm.default_renderer
attribute or by using the renderer
argumentof .
- class
DjangoTemplates
[源代码] - This renderer uses a standalone
DjangoTemplates
engine (unconnected to what you might have configured in the setting). It loads templates first from the built-in formtemplates directory indjango/forms/templates
and then from the installedapps' templates directories using theapp_directories
loader.
If you want to render templates with customizations from your setting, such as context processors for example, use the renderer.
- class
Jinja2
- This renderer is the same as the renderer except thatit uses a
Jinja2
backend. Templatesfor the built-in widgets are located indjango/forms/jinja2
and installedapps can provide templates in ajinja2
directory.
To use this backend, all the widgets in your project and its third-party appsmust have Jinja2 templates. Unless you provide your own Jinja2 templates forwidgets that don't have any, you can't use this renderer. For example, doesn't include Jinja2 templates for its widgetsdue to their usage of Django template tags.
- class
TemplatesSetting
[源代码]
Using this renderer along with the built-in widget templates requires either:
Adding the built-in widgets templates directory in
DIRS
of one of your template engines. To generate that path:
Using this renderer requires you to make sure the form templates your projectneeds can be located.
Widget templates receive a context from . Bydefault, widgets receive a single value in the context, . This is adictionary that contains values like:
name
value
attrs
is_hidden
template_name
Some widgets add further information to the context. For instance, all widgetsthat subclassInput
defineswidget['type']
andMultiWidget
defineswidget['subwidgets']
for looping purposes.
To override widget templates, you must use the renderer. Then overriding widget templates works the same as overriding any other template in your project.