10. Views

10.1. Class Based Views

10.2. Generic Views

  • DetailView
  • EditView
  • ListView

10.2.1. TemplateView

Code Listing 10.15. TemplateView
import datetime
from django.views.generic import TemplateView


class TodayView(TemplateView):
    template_name = 'templates/index.html'

    def get_context_data(self, request, *args, **kwargs):
        return {
            'today': datetime.date.today(),
            'now': datetime.datetime.now(),
        }

10.2.2. RedirectView

Code Listing 10.16. RedirectView
from django.views.generic import RedirectView
from django.urls import path

urlpatterns = [
    path('/index.html', RedirectView.as_view(permanent=False, url='/main')),
]

10.2.3. View

Code Listing 10.17. View
import datetime
from django.http import JsonResponse
from django.views.generic import View


class TodayView(View):
    http_method_names = ['get']

    def get(self, request, *args, **kwargs):
        data = {
            'today': datetime.date.today(),
            'now': datetime.datetime.now(),
        }
        return JsonResponse(status=200, data=data, safe=False)

10.3. Responses

  • HttpResponse
  • JsonReponse

10.4. Decorators

  • @login_required