Working with forms: customization
This episode covers :-
1) How to change the order of the fields.
2) How to render validation errors manually.
- Setup :-
Terminal
cp -fr 22-Forms-Edit 23-Forms-Customization
cd 23-Forms-Customization
source ../venv/bin/activate
- Adding the description field :-
If you want to have more control for the form markup, you can print out the form fields manually. Let’s add a description field to the form and customize the template.
Edit myapp forms.py file and add the description field to the fields list:
myapp/forms
from django import forms
from django.forms import ModelForm
from .models import Flower
class MyForm(ModelForm):
title = forms.CharField(label='Title',
widget = forms.TextInput(attrs={'class': 'form-cont\
rol '}))
description = forms.CharField(label='Description', # < \
here
widget = forms.Textarea(attrs={'class': 'form-contr\
ol '}))
class Meta:
model = Flower
fields = ['title', 'description'] # < here
Edit myapp edit.html template and replace the {{ form }} template variable with these lines:
myapp/templates/myapp/edit.html
{{ form.non_field_errors }}
<div class="form-group">
{{ form.description.errors }}
{{ form.description.label_tag }}
{{ form.description }}
</div>
<div class="form-group">
{{ form.title.errors }}
{{ form.title.label_tag }}
{{ form.title }}
</div>
- In Details :-
- Changing field order :-
If you just need to change the order of the fields, you can do it in the myapp forms.py file:
Update fields list to change order
class Meta:
model = Flower
fields = ['description', 'title'] # < here
If you need more flexibility, edit the myapp edit.html template and print the form fields manually.
- Customizing validation errors :-
Inputing invalid data generates a validation error. Use {{ form.title.errors}} to display those errors manually.
{{ form.non_field_errors }} will render non-field specific general errors.
Note that {{ form }} renders all fields with the errors.
You could go even further and loop through the errors manually. Replace {{ form.title.errors }} with these lines:
Looping through errors manually
{% if form.title.errors %}
<ol class="alert alert-danger">
{% for error in form.title.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %}
Check out the official documentation for more theming options: https://samuli.to/Form-Templates
Summary :-
- You can change the form field order in the form definition: fields =['description', 'title'].
- {{ form }} renders all markup for the fields you specified in the form class. Including the errors.
- For more control, you can use {{ form.title.errors }}, {{ form.title.label_tag }} and {{ form.title }} to render the form markup manually.



No comments:
Post a Comment
If you have any doubts. Please let me know.