28. Views

28.1. Function View

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
from django.http import HttpResponse, HttpResponseNotFound

def my_view(request):
    # ...
    if foo:
        return HttpResponseNotFound('<h1>Page not found</h1>')
    else:
        return HttpResponse('<h1>Page was found</h1>')
from django.http import HttpResponse

def my_view(request):
    # ...

    # Return a "created" (201) response code.
    return HttpResponse(status=201)
from django.http import Http404
from django.shortcuts import render
from polls.models import Poll

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request, 'polls/detail.html', {'poll': p})

28.2. Async Views

  • Since Django 3.1

import datetime
from django.http import HttpResponse

async def current_datetime(request):
    now = datetime.datetime.now()
    html = '<html><body>It is now %s.</body></html>' % now
    return HttpResponse(html)

28.3. Class Based Views

28.4. Generic Views

  • DetailView

  • EditView

  • ListView

28.5. TemplateView

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

28.6. RedirectView

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

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

28.7. View

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

28.8. Responses

  • HttpResponse

  • JsonResponse

28.9. Permissions in Views

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

28.11. Decorators

  • @login_required