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.
Django
Beginner
10 min read
Django Views
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')
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django