Skip to content

Chapter 6: Django Views ​

6.1 Function Views ​

Basic Function Views ​

In Django, views are Python functions that handle HTTP requests and return HTTP responses. Function views are the simplest form of views.

A basic function view example:

python
from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello, World!")

This simple view function takes an HttpRequest object as a parameter and returns an HttpResponse object.

HttpRequest and HttpResponse ​

The HttpRequest object contains all HTTP request information sent by the client, including:

  • request.method: HTTP method (GET, POST, etc.)
  • request.GET: URL parameters
  • request.POST: POST data
  • request.COOKIES: Cookie information
  • request.META: HTTP header information

The HttpResponse object is used to build HTTP responses returned to the client:

python
from django.http import HttpResponse

def my_view(request):
    # Create a simple HTTP response
    response = HttpResponse("Hello, World!")
    
    # Set HTTP headers
    response['Content-Type'] = 'text/plain'
    
    return response

View Decorators ​

Django provides many built-in decorators to enhance view functionality:

python
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods

# Restrict HTTP methods
@require_http_methods(["GET", "POST"])
def my_view(request):
    if request.method == 'GET':
        return HttpResponse("GET request")
    elif request.method == 'POST':
        return HttpResponse("POST request")

# Require user login
@login_required
def protected_view(request):
    return HttpResponse(f"Hello, {request.user.username}!")

Error Handling ​

Django provides exception classes to handle common HTTP errors:

python
from django.http import HttpResponse, Http404
from django.core.exceptions import PermissionDenied

def article_detail(request, article_id):
    try:
        # Try to get the article
        article = Article.objects.get(id=article_id)
    except Article.DoesNotExist:
        # Raise 404 error
        raise Http404("Article does not exist")
    
    # Check permissions
    if not request.user.has_perm('app.view_article'):
        raise PermissionDenied("You don't have permission to view this article")
    
    return HttpResponse(f"Article: {article.title}")

6.2 Class-Based Views ​

View Base Class ​

Django provides class-based views (CBV), which are more flexible and reusable than function views:

python
from django.views import View
from django.http import HttpResponse

class MyView(View):
    def get(self, request):
        return HttpResponse("GET request")
    
    def post(self, request):
        return HttpResponse("POST request")

Generic View Concept ​

Django provides many generic view classes to handle common web development tasks, such as displaying object lists, detail pages, etc.

TemplateView Example ​

TemplateView is used to render templates:

python
from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = "home.html"
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['latest_articles'] = Article.objects.all()[:5]
        return context

Inheritance and Mixins ​

Django's class-based views support multiple inheritance, and you can use Mixin classes to add functionality:

python
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView

class ProtectedListView(LoginRequiredMixin, ListView):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'

6.3 Generic Views in Detail ​

ListView ​

ListView is used to display object lists:

python
from django.views.generic import ListView
from .models import Article

class ArticleListView(ListView):
    model = Article
    template_name = 'articles/article_list.html'
    context_object_name = 'articles'
    paginate_by = 10  # Display 10 items per page

DetailView ​

DetailView is used to display detailed information for a single object:

python
from django.views.generic import DetailView
from .models import Article

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'articles/article_detail.html'
    context_object_name = 'article'

CreateView ​

CreateView is used to create new objects:

python
from django.views.generic import CreateView
from .models import Article
from .forms import ArticleForm

class ArticleCreateView(CreateView):
    model = Article
    form_class = ArticleForm
    template_name = 'articles/article_form.html'
    success_url = '/articles/'

UpdateView ​

UpdateView is used to update existing objects:

python
from django.views.generic import UpdateView
from .models import Article

class ArticleUpdateView(UpdateView):
    model = Article
    fields = ['title', 'content']
    template_name = 'articles/article_form.html'
    success_url = '/articles/'

DeleteView ​

DeleteView is used to delete objects:

python
from django.views.generic import DeleteView
from .models import Article
from django.urls import reverse_lazy

class ArticleDeleteView(DeleteView):
    model = Article
    template_name = 'articles/article_confirm_delete.html'
    success_url = reverse_lazy('article_list')

Complete CRUD Example ​

Here's a complete blog article CRUD example:

python
# views.py
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Article
from .forms import ArticleForm

class ArticleListView(ListView):
    model = Article
    template_name = 'articles/article_list.html'
    context_object_name = 'articles'
    ordering = ['-created_at']

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'articles/article_detail.html'
    context_object_name = 'article'

class ArticleCreateView(CreateView):
    model = Article
    form_class = ArticleForm
    template_name = 'articles/article_form.html'
    success_url = reverse_lazy('article_list')

class ArticleUpdateView(UpdateView):
    model = Article
    form_class = ArticleForm
    template_name = 'articles/article_form.html'
    success_url = reverse_lazy('article_list')

class ArticleDeleteView(DeleteView):
    model = Article
    template_name = 'articles/article_confirm_delete.html'
    success_url = reverse_lazy('article_list')

Corresponding URL configuration:

python
# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('articles/', views.ArticleListView.as_view(), name='article_list'),
    path('articles/<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail'),
    path('articles/new/', views.ArticleCreateView.as_view(), name='article_create'),
    path('articles/<int:pk>/edit/', views.ArticleUpdateView.as_view(), name='article_update'),
    path('articles/<int:pk>/delete/', views.ArticleDeleteView.as_view(), name='article_delete'),
]

Summary ​

Django views are core components for handling user requests:

  1. ✅ Function views are suitable for simple logic, easy to understand and implement
  2. ✅ Class views provide better code reuse and organization
  3. ✅ Generic views greatly reduce repetitive code
  4. ✅ Decorators and Mixins enhance view functionality
  5. ✅ Complete CRUD operation support

Choosing the right view type appropriately can improve development efficiency and code quality.

Next ​

We will learn how to use generic views and custom template tags to build more complex web applications.

7.1 Template Basics →

Contents ​

Back to Course Outline

Released under the [BY-NC-ND License](https://creativecommons.org/licenses/by-nc-nd/4.0/deed.en).