Understanding Django Views: Functions, Classes, and Request Handling
A view in Django is a Python function that processes web requests and returns responses. It serves as the core logic layer between the URL routing and the template system.
View Functions
A basic view function accepts an HTTP request object and returns an HTTP response.
from django.http import HttpResponse
import datetime
def show_current_time(request):
current_time = datetime.datetime.now()
response_content = f"<html><body>Current time: {current_time}</body></html>"
return HttpResponse(response_content)
Response Objects
Django provides several response types for differant scenarios:
| Response Type | Description | Example |
|---|---|---|
HttpResponse |
Returns plain text or HTML content | return HttpResponse("Welcome!") |
render |
Renders a template with context data | return render(request, "profile.html", {"user": "alice", "score": 95}) |
redirect |
Redirects to another URL | return redirect("/dashboard/") |
JSON Responses
For API development, Django offers JsonResponse to return JSON-formatted data.
from django.http import JsonResponse
# Returning a dictionary
def user_data(request):
user_info = {"username": "alex", "level": 3}
return JsonResponse(user_info)
# Returning a list (requires safe=False)
def scores_list(request):
scores = [85, 92, 78]
return JsonResponse(scores, safe=False)
When dealing with non-ASCII characters (like Chinese), set ensure_ascii=False to preserve the original encoding:
def localized_data(request):
data = {"city": "北京", "population": 21540000}
return JsonResponse(data, json_dumps_params={"ensure_ascii": False})
Function-Based vs Class-Based Views
Django supports two approaches to writing views:
Function-Based Views (FBV): Tradisional Python functions.
Class-Based Views (CBV): Views defined as classes with methods for different HTTP methods.
# URL configuration
from django.urls import path
from . import views
urlpatterns = [
path('auth/', views.AuthView.as_view()),
]
# views.py
from django.views import View
from django.http import HttpResponse
class AuthView(View):
def get(self, request):
return HttpResponse("GET: Display login form")
def post(self, request):
return HttpResponse("POST: Process login data")
def dispatch(self, request, *args, **kwargs):
# Custom preprocessing
print("Request processing started")
result = super().dispatch(request, *args, **kwargs)
print("Request processing completed")
return result
The dispatch() method acts as an entry point, routing requests to appropriate handler methods (get, post, etc.).
File Uploads
Handling file uploads requires specific form settings and backend processing.
Frontend requirements:
- Form method must be
POST - Form enctype must be
multipart/form-data
Backend processing:
def handle_upload(request):
if request.method == 'POST':
uploaded_file = request.FILES.get('document')
if uploaded_file:
filename = uploaded_file.name
with open(filename, 'wb') as destination:
for chunk in uploaded_file.chunks():
destination.write(chunk)
return HttpResponse(f"File '{filename}' uploaded successfully")
return HttpResponse("No file received")
Request Object Attributes
The Django HttpRequest object provides numerous attributes for accessing request data:
request.GET: Dictionary-like object containing GET parametersrequest.POST: Dictionary-like object containing POST form datarequest.body: Raw request body (useful for non-form data like JSON)request.path/request.path_info: URL path componentrequest.get_full_path(): URL path with query stringrequest.method: HTTP method (e.g., "GET", "POST")request.encoding: Character encoding of submitted datarequest.META: Dictionary containing HTTP headersrequest.FILES: Dictionary containing uploaded filesrequest.COOKIES: Dictionary containing cookiesrequest.session: Session datta dictionary
Important notes:
- Use
request.method == "POST"instead of checkingrequest.POSTto determine if a request uses POST method - For multi-value form fields (like checkboxes), use
request.POST.getlist('field_name') - File data is only available in
request.FILESwhen the form usesenctype="multipart/form-data"