Django — Views
Function-Based Views
# blog/views.py
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
def home(request):
return HttpResponse("Hello, World!")
def post_list(request):
return render(request, 'blog/list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/detail.html', {'post': post})
Class-Based Views
from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
model = Post
template_name = 'blog/list.html'
context_object_name = 'posts'
class PostDetailView(DetailView):
model = Post
template_name = 'blog/detail.html'
context_object_name = 'post'
Request Object
def my_view(request):
request.method # 'GET' or 'POST'
request.GET # Query parameters
request.POST # Form data
request.FILES # Uploaded files
request.user # Current user
request.session # Session data
HttpResponse
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
def my_view(request):
return HttpResponse("Hello")
return JsonResponse({'key': 'value'})
return HttpResponseRedirect('/success/')
Mini Practice
- Create function-based views
- Create class-based views
- Access request data
- Return different response types
Up Next
Continue with Templates — rendering HTML with templates.
Related Topics
Frequently Asked Questions about Views
What is Views in Django?
Views is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Views?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Views.
Why is Views important in Django?
Views is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.