From Classy Class Based Views CreateView
View for creating a new object, with a response rendered by a template.
Attributes
Three attributes are required to get the template to render. Two we’ve seen before (queryset
and template_name
). The new one we haven’t see before is the fields
attribute.
- fields: specifies what fields from the model or queryset will be displayed on the rendered template. You can you set
fields
to__all__
if you want to return all of the fields
Example
views.py
queryset = Person.objects.all()
fields = '__all__'
template_name = 'rango/person_form.html'
urls.py
path('create_view/', views.myCreateView.as_view(), name='create_view'),
\<template>.html
{% extends 'base.html' %}
<h1>
{% block title %}
{{ title }}
{% endblock %}
</h1>
{% block content %}
<h3>{{ type }} View</h3>
<form action="." method="post">
{% csrf_token %}
<table>
{{ form.as_p }}
</table>
<button type="submit">SUBMIT</button>
</form>
{% endblock %}
Diagram
A visual representation of how CreateView
is derived can be seen here:
Conclusion
A simple way to implement a form to create items for a model. We’ve completed step 1 for a basic CRUD application.