About Lesson
What is a Model Form?
Model forms are used to automatically create forms from Django models. This saves time by automatically generating fields that correspond to the model’s attributes.
Creating a Model Form
- Define the Model:
- Create the Model Form: In
forms.py
, create a form based on the model: - Rendering the Model Form: In the view:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content']
from django.shortcuts import render
from .forms import PostForm
def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save() # Save the data to the database
return redirect('success')
else:
form = PostForm()
return render(request, 'create_post.html', {'form': form})
Join the conversation