The django.views.generic.create_update.create_object view renders a generic view that displays a form for creating objects. The create_object view requires a model argument containing the model of the class you want to create. A Form object is generated for the model and is passed to the template in the context variable form.
By the Way
If the object has validation errors, create_object displays them.
The form is displayed if accessed with a GET request, and the object is saved on a POST request.
Watch Out!
The create_object function actually modifies data in the database. You should use the login_required object to make certain that users are logged in before accessing the view.
The required argument is model.
The optional arguments are post_save_redirect, login_required, template_name, template_loader, extra_context, and context_processors.
The context variables are form and extra_context.
The default template_name is app_label/model_name_form.html (such as People/Person_form.html).
The following code snippet shows an example of defining a generic create_object view in the URLconf file:
blog_info = { 'model' : Blog, 'post_save_redirect' : '/blog/list', } urlpatterns += patterns('', (r'^generic/blog_add/$', create_update.create_object, blog_info),
The following template code snippet shows an example of accessing the context variable form in a template:
<form action="" method="post"> <p><label for"id_text">Title:</label>{{ form.title}}</p> <p><label for"id_by">By:</label>{{ form.text }}</p> <input type="submit" />
Try It Yourself: Use a Generic View to Implement an Object Creation FormIn this section, you will use the create_object generic view to display a Quote object creation form and create Quote objects. Follow these steps to create a template and update the URLconf file to enable the view:
|