How django function based view works

What is view in Django

  • A view is a callable which takes a request and returns a response.
  • A view is a “type” of Web page in your Django application that generally serves a specific function and has a specific template.
  • In Django, web pages and other content are delivered by views. Each view is represented by a Python function (or method, in the case of class-based views).
  • Django will choose a view by examining the URL that’s requested (to be precise, the part of the URL after the domain name).
  • Each view is responsible for doing one of two things: returning an HttpResponse object containing the content for the requested page, or raising an exception such as Http404.
  • What views can do
    • Your view can read records from a database, or not.
    • It can use a template system such as Django’s – or a third-party Python template system – or not.
    • It can generate a PDF file, output XML, create a ZIP file on the fly, anything you want, using whatever Python libraries you want.

In this article, we will see how to work with function based views in Django. There is lot of debate on function based views vs class based views. Let us look at pros and cons of function based views


  • Simple to implement
  • Easy to read
  • Explicit code flow
  • Straightforward usage of decorators


  • Hard to extend and reuse the code
  • Handling of HTTP methods via conditional branching

If you look at pros and cons, its not a bad idea to stick with function based views again, it based on each developers perception and someone wants to use class based views, nothing wrong in that.

Let us create simple project which will render views using function based views.

How urls are structured

from django.urls import path

from . import views

# urlpatterns = [
#     path('', views.index, name='index'),
#     path('details', views.details, name='index'),
#     path('vote',, name='vote'),
# ]
app_name = 'polls'
urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('/vote/',, name='vote'),

And function based views are defined as below

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from django.urls import reverse
from .models import Question, Choice

def detail(request, question_id):
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        selected_choice.votes += 1
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(,)))

What is the difference between render and HttpResponse
Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.  Render is basically a simple wrapper around a HttpResponse .

you can use HttpResponse to return others things as well in the response, not just rendering templates.
If you are making AJAX call, you can return JSON as below

return HttpResponse(jsonObj, mimetype='application/json')


return HttpResponseRedirect(""):

It will return an HTTP status code 302 [redirect] along with the new URL. This should be used only to redirect to another page (e.g. after successful form POST)


return redirect('')

redirect gives the HttpResponseRedirect for the argument you have passed.





Leave a Reply

Your email address will not be published. Required fields are marked *