📜  createview - Python (1)

📅  最后修改于: 2023-12-03 15:14:17.004000             🧑  作者: Mango

Introduction to CreateView in Python

In Django, CreateView is a class-based view that provides a way to create objects and save them to the database using a form.

Syntax
from django.views.generic.edit import CreateView

class MyCreateView(CreateView):
    model = MyModel
    form_class = MyForm
    success_url = '/success/url/'
    # additional options
Parameters
  • model: the model used to create the object.
  • form_class: the form used to create the object.
  • success_url: the URL to redirect after a successful creation.
  • template_name: the name of the template used to render the form, defaults to the same name as the model.
  • context_object_name: the name of the variable used to store the created object in the template context.
  • extra_context: a dictionary of extra context to add to the template context.
  • prefix: the prefix used in the form data, default is the model name in lowercase.
  • initial: a dictionary of initial values for the form.
  • form_kwargs: a dictionary of additional keyword arguments to pass to the form.
  • success_message: a message displayed on the success page.
Example

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.

Conclusion

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.