Map URLs to Python functions and classes. Pass data from models to templates. Understand function-based views and class-based views.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('posts//', views.post_detail, name='post_detail'),
] 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, slug):
post = get_object_or_404(Post, slug=slug, published=True)
return render(request, 'blog/post_detail.html', {'post': post})from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
model = Post
queryset = Post.objects.filter(published=True)
template_name = 'blog/post_list.html'
context_object_name = 'posts'
paginate_by = 10
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'ListView, DetailView, CreateView, UpdateView, DeleteView cover 80% of web app views.render(request, template, context) — the three things every view does.get_object_or_404 returns the object or a 404 response. Use it instead of .get() in views.