Django: CreateView
1 min readMar 25, 2020
1. [myproject/myapp/views.py]
from myapp.models import Bike
from django.views.generic.edit import CreateView
class BikeCreateView(CreateView):
model = Bike
template_name = 'bike_create.html'
fields = ['type','price']
2. [myproject/myapp/templates/bike_create.html]
<h2>Create Bike</h2>
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
3. [myproject/myproject/urls.py]
from django.contrib import admin
from django.urls import path
from myapp.views import BikeCreateViewurlpatterns = [
path('bike_create/', BikeCreateView.as_view(),name='bike_create'),
]
Result
- create a new record
2. redirect to the new created record when success