11. Views

11.1. Class Based Views

11.2. Generic Views

  • DetailView

  • EditView

  • ListView

11.3. TemplateView

Code 11.24. 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(),
        }

11.4. RedirectView

Code 11.25. RedirectView
from django.views.generic import RedirectView
from django.urls import path

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

11.5. View

Code 11.26. 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)

11.6. Responses

  • HttpResponse

  • JsonResponse

11.7. Permissions in Views

11.8. Class Based Views

from django.contrib.auth.mixins import PermissionRequiredMixin

class MyView(PermissionRequiredMixin, View):
    permission_required = 'polls.can_vote'
    # Or multiple of permissions:
    permission_required = ('polls.can_open', 'polls.can_edit')

11.9. Decorators

  • @login_required