Core Concepts
Views and URLs
Create views to handle requests and configure URL routing in Django.
Views
A view is a Python function or class that:
- Receives an HTTP request
- Processes it (fetches data, runs logic)
- Returns an HTTP response
Function-Based Views (FBV)
Simple Python functions. Great for simple endpoints.
Class-Based Views (CBV)
Django provides generic class-based views that handle common patterns (list, detail, create, update, delete) with minimal code.
URL Configuration
The urls.py file maps URL patterns to views. Use path() for simple patterns and re_path() for regex.
Example
python
# blog/views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, JsonResponse
from .models import Post, Category
# Function-based view
def post_list(request):
posts = Post.objects.filter(status='published').order_by('-published_at')
# Filter by category
category_slug = request.GET.get('category')
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
posts = posts.filter(category=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 views (more concise)
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')
# API view (JSON response)
def api_posts(request):
posts = Post.objects.filter(status='published').values(
'id', 'title', 'slug', 'excerpt', 'created_at'
)
return JsonResponse(list(posts), safe=False)
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.PostListView.as_view(), name='post-list'),
path('<slug:slug>/', views.post_detail, name='post-detail'),
path('api/posts/', views.api_posts, name='api-posts'),
]
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
]Try it yourself — PYTHON