What is views?

Patel NayanPatel Nayan
3 min read

In Django, a view is simply a Python function (or class) that takes a web request and returns a web response.

Key points

  • Input: an HttpRequest object, which carries data about the incoming request (URL parameters, submitted form data, cookies, etc.).

  • Output: an HttpResponse object, which could render an HTML template, redirect, raise a 404, stream a file, return JSON… anything you want to send back to the browser or client.

Types of views in django:

Django views come in two broad flavors:

  1. Function‑Based Views (FBVs)

    • What they are: Plain Python functions that receive an HttpRequest and return an HttpResponse.

    • When to use:

      • Simple, custom logic that doesn’t fit a generic pattern.

      • You want full control over request handling without the abstraction layer of classes.

    • Example:

        from django.shortcuts import render, get_object_or_404
        from .models import Question
      
        def detail(request, question_id):
            q = get_object_or_404(Question, pk=question_id)
            return render(request, 'polls/detail.html', {'question': q})
      
  2. Class‑Based Views (CBVs)

    • What they are: Python classes (subclasses of django.views.View) with methods like get(), post(), etc., that handle different HTTP verbs.

    • Why use them:

      • Promote reuse via inheritance and mixins.

      • Built‑in generic implementations for common patterns.

      • Cleaner separation of GET vs. POST logic.

    • Basic Structure:

        from django.views import View
        from django.shortcuts import render
      
        class HelloView(View):
            def get(self, request):
                return render(request, 'hello.html')
      
  3. Generic Class‑Based Views (GCBVs)
    Django ships with a set of “batteries‑included” CBVs for the most common web‑app patterns:

    | View | Purpose | | --- | --- | | TemplateView | Renders a template with a context. | | ListView | Displays a list of objects (e.g. rows). | | DetailView | Shows detail for a single object. | | CreateView | Displays a form for creating an object; saves on valid POST. | | UpdateView | Form for editing an existing object. | | DeleteView | Asks for confirmation then deletes object. | | FormView | Renders a form and processes it. | | RedirectView | Immediately redirects to a different URL. |

     from django.views.generic import ListView
     from .models import Question
    
     class QuestionListView(ListView):
         model = Question
         template_name = 'polls/question_list.html'
         context_object_name = 'questions'
    
  4. Mixins
    — Small building‑block classes that you can combine with CBVs to add behavior (e.g. LoginRequiredMixin, PermissionRequiredMixin, FormMixin).

     from django.contrib.auth.mixins import LoginRequiredMixin
     from django.views.generic import CreateView
     from .models import Choice
    
     class ChoiceCreateView(LoginRequiredMixin, CreateView):
         model = Choice
         fields = ['question', 'choice_text']
    
  5. Decorator‑Based Views
    — You can apply decorators (like @login_required, @permission_required) to FBVs, or use mixins on CBVs, to enforce authentication, permissions, caching, etc.

  6. REST‑Style/API Views (when using Django REST Framework)
    If you add DRF, you get:

    • APIView: the base class for REST endpoints.

    • Generic API views & ViewSets: e.g. ListCreateAPIView, ModelViewSet, which mirror Django’s generic CBVs but for JSON/serializers instead of HTML/templates.


How to choose?

  • FBV if your view logic is very simple or highly customized.

  • CBV/GCBV if you see yourself repeating the same boilerplate (e.g. “show list → show detail → form to create → form to update”) and want to leverage inheritance/mixins.

  • DRF’s APIView/ViewSet for building RESTful JSON APIs.

1
Subscribe to my newsletter

Read articles from Patel Nayan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Patel Nayan
Patel Nayan

Science student.