Here, we'll explain the basics of django's class-based views (general-purpose views).
Write in views.py
under the application directory.
Suppose you want to use SampleModel
from models.py
as a model and SampleForm
from forms.py
as a form.
TemplateView
This is the simplest form of class view. It can be used to create various pages.
views.py
from django.views import generic
class SampleTemplate(generic.TemplateView):
template_name = 'app/app_template.html'
In addition, template_name
that specifies the HTML file to be a template will be used by default even if it is not specified at the time of class definition if it is app name / app name_view name.html
. The same is true for the other views described below.
ListView
It can be used for pages that list multiple records, such as the article list page of a blog.
views.py
from django.views import generic
from .model import SampleModel
class SampleList(generic.ListView):
model = SampleModel
template_name = 'app/app_list.html'
paginate_by = 10 #When adding pagination
model
specifies the model that contains the records to display on the page.
CreateView
It can be used for pages that create new records, such as creating new articles for blogs.
views.py
from django.urls import reverse_lazy
from django.views import generic
from .model import SampleModel
from .forms import SampleForm
class SampleCreate(generic.CreateView):
model = SampleModel
form_class = SampleForm
template_name = 'app/app_create.html'
success_url = reverse_lazy('app:app_list')
A form screen is created based on the form specified by form_class
.
Also, success_url
specifies the page to transition to after successful article creation. Details will be explained in the article ʻurls.py`.
DetailView
It can be used for pages that display record details, such as individual pages of blog posts.
views.py
from django.views import generic
from .model import SampleModel
from .forms import SampleForm
class SampleDetail(generic.Detail):
model = SampleModel
template_name = 'app/app_detail.html'
UpdateView
It can be used for pages that update the record contents once created, such as the edit screen of blog articles.
views.py
from django.urls import reverse_lazy
from django.views import generic
from .model import SampleModel
from .forms import SampleForm
class SampleUpdate(generic.UpdateView):
model = SampleModel
form_class = SampleForm
template_name = 'app/app_update.html'
success_url = reverse_lazy('app:app_list')
DeleteView
It can be used for pages that delete created records, such as the delete screen for blog articles.
views.py
from django.urls import reverse_lazy
from django.views import generic
from .model import SampleModel
from .forms import SampleForm
class SampleDelete(generic.DeleteView):
model = SampleModel
template_name = 'app/app_delete.html'
success_url = reverse_lazy('app:app_list')
Here's the basics of django's class-based views. Next time, I'll talk about function-based views.
Recommended Posts