Performance: ModelForm for model-backed forms
This affects page load speed and interaction responsiveness by controlling how form HTML is generated and validated on the server before sending to the client.
Jump into concepts and practice - no test required
from django.forms import ModelForm from .models import Person class PersonForm(ModelForm): class Meta: model = Person fields = ['name', 'age']
from django import forms class MyForm(forms.Form): name = forms.CharField(max_length=100) age = forms.IntegerField() # Manually syncing form fields with model fields
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual form fields | More complex HTML with possible extra wrappers | Multiple reflows if form is large | Higher paint cost due to complex DOM | [X] Bad |
| ModelForm usage | Simpler, consistent HTML structure | Single reflow on form load | Lower paint cost with optimized DOM | [OK] Good |
ModelForm in Django?ModelForm?class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title']
form = BookForm({'title': 'Django Basics', 'author': 'Alice'})
if form.is_valid():
book = form.save()
print(book.author)
else:
print('Invalid form')ModelForm definition?class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = 'name, age'ModelForm for a model Product with fields name, price, and stock. You want the form to include only name and price, but also want to add a custom validation that price must be positive. Which is the best way to do this?