Skip to content

Q&A · Answered

How to create Django forms

asked 9 months, 1 week ago 581 views 1 answer
43

What is the difference between Form and ModelForm in Django?

1 Answer

One accepted
12

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
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
            pass

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.