📅  最后修改于: 2023-12-03 15:14:17.004000             🧑  作者: Mango
In Django, CreateView is a class-based view that provides a way to create objects and save them to the database using a form.
from django.views.generic.edit import CreateView
class MyCreateView(CreateView):
model = MyModel
form_class = MyForm
success_url = '/success/url/'
# additional options
Let's assume we have a model called Employee
and a form called EmployeeForm
. We want to create a new employee object using the CreateView
.
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .models import Employee
from .forms import EmployeeForm
class EmployeeCreateView(CreateView):
model = Employee
form_class = EmployeeForm
success_url = reverse_lazy('employee_list')
template_name = 'employee_form.html'
In the above example, we create a new class called EmployeeCreateView
that extends the CreateView
. We set the model
to Employee
and the form_class
to EmployeeForm
. The success_url
is set to employee_list
using the reverse_lazy
function. The template_name
is set to employee_form.html
.
In conclusion, the CreateView
in Django provides a simple and efficient way to create objects and save them to the database using a form. The above introduction provides a basic understanding of the syntax and parameters of the CreateView
. The best way to learn how to use it is to practice coding and implement it yourself.