Django — Forms
Basic Form
# blog/forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'published']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
}
Regular Form
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
Form in View
def post_create(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/form.html', {'form': form})
Form Template
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
Form Validation
class PostForm(forms.ModelForm):
def clean_title(self):
title = self.cleaned_data.get('title')
if len(title) < 5:
raise forms.ValidationError("Title must be at least 5 characters")
return title
Mini Practice
- Create a ModelForm
- Create a regular Form
- Handle form submission in views
- Add custom validation
Up Next
Continue with Form Validation — validating form data.
Related Topics
Frequently Asked Questions about Forms
What is Forms in Django?
Forms is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Forms?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Forms.
Why is Forms important in Django?
Forms is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.