Tuesday, January 3, 2023

class based views instead of function based views

 class view contains predefined functionalities, so can skip many routine things.

like passing the template to render function, we can simply pass the template_note to class variable.



views.py
----
from django.shortcuts import render
from django.http HttpResponse
from datetime import datetime
##from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView,ListView,DetailView

class HomeView(TemplateView):
  template_name = 'home/welcome.html'
  extra_context = {'today': datetime.today()}

class AuthorizedView(LoginRequiredMixin,TemplateView):
  template_name = 'home/authorized.html'
  login_url = "/admin"

class NotesListView(ListView):
  model = Notes
  context_object_name = "notes"
  template_name = "notes/notes_list.html" ##optional to pass template as uses default template

class NotesDetailView(DetailView):
  model = Notes
  context_object_name = "note"

urls.py
----
urlpatterns = [
 path('home',views.HomeView.as_view()), ## path('home',views.home)
 path('home',views.AuthorizedView.as_view()),
 path('notes',views.NotesListView.as_view()),
 path('notes/<int:pk>',NotesDetailView.as_view()),
]

No comments:

Post a Comment