CreateView helps you quickly make a page where users can add new items to your database without writing a lot of code.
0
0
CreateView for object creation in Django
Introduction
You want a simple form page to add new blog posts.
You need a user registration page that saves new users.
You want to let users submit feedback or comments.
You want to create new products in an online store admin panel.
Syntax
Django
from django.views.generic.edit import CreateView from .models import YourModel class YourModelCreateView(CreateView): model = YourModel fields = ['field1', 'field2'] template_name = 'yourmodel_form.html' success_url = '/success/'
model tells Django which database table to add to.
fields lists which fields to show in the form.
Examples
This creates a form to add new books with title and author fields.
Django
class BookCreateView(CreateView): model = Book fields = ['title', 'author'] success_url = '/books/'
This sets a custom template and redirects to a welcome page after signup.
Django
class UserCreateView(CreateView): model = User fields = ['username', 'email', 'password'] template_name = 'users/signup.html' success_url = '/welcome/'
Sample Program
This example shows a Task model and a CreateView to add new tasks with a title and description. The form uses a simple template and redirects to a success page after saving.
Django
from django.urls import path from django.views.generic.edit import CreateView from django.db import models from django.shortcuts import render # Model definition class Task(models.Model): title = models.CharField(max_length=100) description = models.TextField() # CreateView for Task class TaskCreateView(CreateView): model = Task fields = ['title', 'description'] template_name = 'task_form.html' success_url = '/tasks/success/' # URL patterns urlpatterns = [ path('tasks/new/', TaskCreateView.as_view(), name='task-create'), ] # Template (task_form.html) example: # <form method="post"> # {% csrf_token %} # {{ form.as_p }} # <button type="submit">Add Task</button> # </form>
OutputSuccess
Important Notes
Always include {% csrf_token %} in your form template for security.
You can customize the form by overriding form_valid() method in your CreateView.
If you don't set success_url, Django will try to call get_absolute_url() on your model.
Summary
CreateView makes it easy to build pages for adding new database records.
Set model, fields, and success_url to get started quickly.
Use a simple template with {{ form.as_p }} and {% csrf_token %} for the form.