Django
Beginner
1 min read
ModelForms and Saving to the Database
Example
# blog/forms.py — ModelForm
from django import forms
from .models import Post, Tag
class PostModelForm(forms.ModelForm):
# Extra form-only field (not in the model)
tag_names = forms.CharField(
required=False,
help_text='Comma-separated tags (e.g. python, django).',
widget=forms.TextInput(attrs={'placeholder': 'python, django, web'}),
)
class Meta:
model = Post
fields = ['title', 'body', 'category', 'status']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control', 'rows': 10}),
'status': forms.Select(attrs={'class': 'form-select'}),
}
labels = {'body': 'Content'}
def save(self, commit=True):
post = super().save(commit=False)
if commit:
post.save()
# Handle the extra tag_names field
tag_names = self.cleaned_data.get('tag_names', '')
if tag_names:
for name in [t.strip() for t in tag_names.split(',') if t.strip()]:
tag, _ = Tag.objects.get_or_create(
name=name,
defaults={'slug': name.lower().replace(' ', '-')},
)
post.tags.add(tag)
self.save_m2m()
return post
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django