Django's model forms are a powerful tool that makes interacting with your database easy and seamless. They are essentially a way for you to create forms from your models.
is_valid()
.save()
method to save your form data to the database. This method takes care of both creating new records and updating existing ones.Let's create a simple blog post model form.
from django import forms
from .models import BlogPost
class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['title', 'content', 'author']
def clean_title(self):
title = self.cleaned_data.get('title')
if not title:
raise forms.ValidationError("Title is required.")
return title
In this example, BlogPostForm
is a model form based on the BlogPost
model. It includes three fields: title
, content
, and author
. The clean_title
method is a custom validation method for the title
field. If the title
field is empty, it raises a ValidationError
.
To save this form data to the database, you can use the save()
method:
if request.method == 'POST':
form = BlogPostForm(request.POST)
if form.is_valid():
form.save()
In this tutorial, you learned how to use Django's model forms to interact with your database. You learned how to create a model form, validate it, and save it to the database.
UserProfile
model with fields username
, email
, and bio
. Write a custom validation method for the email
field to check if the email is already in use.UserProfileForm
to include password and password confirmation fields. Add validation to make sure the two password fields match.UserProfileForm
on a template. If the form is valid, save the data to the database and redirect the user to a success page.For further practice, try creating model forms for other models in your project and experiment with different types of validation. Happy coding!