Performance: Form error handling
MEDIUM IMPACT
Form error handling affects page responsiveness and visual stability during user input and form submission.
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 |