Performance: Form error handling
Form error handling affects page responsiveness and visual stability during user input and form submission.
Jump into concepts and practice - no test required
def my_view(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): # process data return redirect('success') else: form = MyForm() return render(request, 'form.html', {'form': form}) <!-- In form.html template --> <form method="post"> {% csrf_token %} {{ form.as_p }} {% if form.errors %} <div role="alert" aria-live="assertive"> {{ form.errors }} </div> {% endif %} <button type="submit">Submit</button> </form>
def my_view(request): if request.method == 'POST': form = MyForm(request.POST) if not form.is_valid(): errors_html = '' for field, errors in form.errors.items(): errors_html += f'<div>{field}: {errors}</div>' return HttpResponse(f'<form>{form.as_p()}</form>{errors_html}') else: form = MyForm() return render(request, 'form.html', {'form': form})
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual error HTML injection | Multiple nodes added dynamically | Multiple reflows per error | High paint cost due to layout shifts | [X] Bad |
| Template-based error rendering | Minimal DOM updates with existing nodes | Single reflow on error display | Low paint cost with stable layout | [OK] Good |
form.is_valid() do in Django form handling?form.is_valid()form.errors, which returns a dictionary of errors.{{ form.errors }} in the template displays the errors properly.print(form.errors) output if the 'email' field is left empty?class ContactForm(forms.Form):
email = forms.EmailField(required=True)
form = ContactForm(data={'email': ''})
form.is_valid()
print(form.errors)form.is_valid(), form.errors contains the error message for the empty 'email' field.form = MyForm(request.POST)
if form.is_valid:
form.save()form.is_valid without parentheses, so it references the method but does not call it.There are errors in the form.
{% endif %} only shows a message if errors exist, no details.