Introduction
Views handle the logic of your application. They take a web request and return a web response. Django supports both function-based views (FBVs) and class-based views (CBVs).
Function-based views
# views.py
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.filter(published=True)
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]Class-based views
from django.views.generic import ListView, DetailView
class PostListView(ListView):
model = Post
template_name = 'blog/post_list.html'
context_object_name = 'posts'
queryset = Post.objects.filter(published=True)
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'Assignment
- Complete Django tutorial Part 3 (views).
- Create views for listing and viewing blog posts.
- Convert your function-based views to class-based views.