43
What is the difference between Form and ModelForm in Django?
Loading...
Q&A · Answered
What is the difference between Form and ModelForm in Django?
Accepted answer
from django import forms
from .models import Article
# Regular Form
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
# ModelForm
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'content', 'category']
widgets = {
'content': forms.Textarea(attrs={'rows': 5}),
}
# Usage in view
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process form
passSay what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.