4.10. Views

4.10.1. Class Based Views

4.10.2. Generic Views

  • DetailView

  • EditView

  • ListView

4.10.2.1. TemplateView

Listing 506. 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(),
        }

4.10.2.2. RedirectView

Listing 507. RedirectView
from django.views.generic import RedirectView
from django.urls import path

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

4.10.2.3. View

Listing 508. 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)

4.10.3. Responses

  • HttpResponse

  • JsonReponse

4.10.4. Permissions in Views

4.10.4.1. 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')

4.10.4.2. Decorators

  • @login_required