PODSUMOWANIE:
- Nie wszystkie wbudowane widoki w Django są implementowane jako class-based views.
- Większość nowoczesnych widoków jest implementowana jako class-based views.
- Starsze i prostsze widoki, szczególnie związane z uwierzytelnianiem i adminem, mogą być function-based views.
LISTA WBUDOWANYCH WIDOKÓW:
- 1. Widoki genericzne (CBV, django.views.generic):
- ListView
- pobiera wszystkie elementy w modelu / tabeli
- DetailView
- pobiera dokładnie jeden obiekt modelu / tabeli spełniający kryteria zdef. w url.py
- CreateView
- UpdateView
- DeleteView
- 2. Widoki związane z uwierzytelnianiem (CBV):
- LoginView, LogoutView, PasswordResetView, PasswordChangeView
- 3. Widoki ogólnego przeznaczenia (CBV):
- RedirectView, TemplateView
- 4. Function-Based Views (FBV):
- Widoki związane z uwierzytelnianiem (logout_then_login, password_reset_done)
- Widoki dla admina (sporo)
# Ad1. CBV Widoki genericzne, przykład:
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('add/', views.AddView.as_view(), name='add'),
path('posts/', views.PostsView.as_view(), name='posts'),
path('<slug:slug>/', views.SingleView.as_view(), name='single'),
path('edit/<int:pk>/', views.EditView.as_view(), name='edit'),
path('delete/<int:pk>/', views.DeleteCustomView.as_view(), name='delete'),
]
from django.views.generic import ListView, DetailView, UpdateView, DeleteView
class IndexView(ListView):
model = Core
template_name = "core/index.html"
context_object_name = "index"
# context_object_name = "object_list" (default)
class SingleView(DetailView):
model = Core
template_name = "core/single.html"
context_object_name = "post"
class PostsView(ListView):
model = Core
template_name = "core/posts.html"
context_object_name = "post_list"
class AddView(CreateView):
model = Core
# fields = ["title"]
fields = "__all__"
template_name = "core/add.html"
success_url = reverse_lazy("core:posts")
# context_object_name = "object_list" (default)
class EditView(UpdateView):
model = Core
fields = "__all__"
template_name = "core/edit.html"
pk_url_kwarg = "pk"
success_url = reverse_lazy("core:posts")
# context_object_name = "object_list" (default)
class DeleteCustomView(DeleteView):
model = Core
# fields = "__all__"
template_name = "core/confirm-delete.html"
pk_url_kwarg = "pk"
success_url = reverse_lazy("core:posts")
# context_object_name = "object_list" (default)