SyntaxStudy
Sign Up
Django Beginner 10 min read

Django Views

A view in Django is a Python function or class that takes a web request and returns a web response. Views contain the logic for what data to display and how to display it.

Example
# blog/views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Post, Category

# Function-based view
def post_list(request):
    posts = Post.objects.filter(status='published').select_related('author', 'category')
    return render(request, 'blog/post_list.html', {'posts': posts})

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug, status='published')
    return render(request, 'blog/post_detail.html', {'post': post})

# Class-based view
from django.views.generic import ListView, DetailView

class PostListView(ListView):
    model = Post
    template_name = 'blog/post_list.html'
    context_object_name = 'posts'
    paginate_by = 10

    def get_queryset(self):
        return Post.objects.filter(status='published')