Back
Featured image of post Views in Django

Views in Django

A view function, or view for short, is a Python function that takes a web request and returns a web response. This response can be the HTML contents of a web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything

for example

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def home(request):
    return HttpResponse('home')

def products(request):
    return HttpResponse('products')

def customer(request):
    return HttpResponse('customer')

all kinds of views django

Function Base View

The simplicity of FBVs comes at the expense of code reuse: FBVs don’t have the same ability to inherit from superclasses the way that CBVs do. They do have the advantage of being more functional in nature, which lends itself to a number of interesting strategies.

We follow these guidelines when writing FBVs:

  • Less view code is better.
  • Never repeat code in views.
  • Views should handle presentation logic. Try to keep business logic in models when possible, or in forms if you must.
  • Keep your views simple.
  • Use them to write custom 403, 404, and 500 error handlers.
  • Complex nested-if blocks are to be avoided.

for example

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})

for example

from .views import detail

urlpatterns = [
    path('detail/', detail),
]
Async Function Base View

As well as being synchronous functions, views can also be asynchronous (“async”) functions, normally defined using Python’s async def syntax. Django will automatically detect these and run them in an async context. However, you will need to use an async server based on ASGI to get their performance benefits.

example

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)

Class Base View Django

A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views.

for example

# some_app/views.py

from django.views.generic import TemplateView

class AboutView(TemplateView):
    template_name = "about.html"

route

# some_app/urls.py
from .views import AboutView

urlpatterns = [
    path('about/', AboutView.as_view()),
]

Conclusion

Both function-based views (FBVs) and class-based views (CBVs) are a core part of Django. We recommend that you understand how to use both types of views.

Licensed under CC BY-NC-SA 4.0
Last updated on Jan 11, 2022 23:42 +0700
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy