Implementing Django Views using Function and Class Based Approaches
Django views serve as the logic layer of a web application, responsible for processing client requests and returning the appropriate responses. A view is essentially a Python function or class that accepts an HttpRequest object and returns an HttpResponse object, which can contain HTML, JSON data, or redirects.
Function-Based Views (FBV)
Function-Based Views are the most straightforward way to implement logic in Django. Each view is defined as a standard Python function. This approach is highly readable and suitable for simple logic.
To implement an FBV, first define the URL pattern:
# core/urls.py
from django.urls import path
from web_app.views import display_welcome
urlpatterns = [
path("welcome/", display_welcome),
]
Then, create the corresponding logic in the application's view file:
# web_app/views.py
from django.http import HttpResponse
def display_welcome(request):
return HttpResponse("Welcome to the application homepage.")
Class-Based Views (CBV)
Class-Based Views offer a more structured approach, leveraging object-oriented programming to handle different HTTP methods. By inheriting from django.views.View, logic for GET, POST, and other methods can be separated into distinct class methods.
Routing for a CBV requires the as_view() method to transform the class into a callable function:
# core/urls.py
from django.urls import path
from web_app.views import ArticleManager
urlpatterns = [
path("articles/", ArticleManager.as_view()),
]
In the view file, define the class and its methods:
# web_app/views.py
from django.http import HttpResponse
from django.views import View
class ArticleManager(View):
def get(self, request):
return HttpResponse("Retrieving the article list via GET request.")
def post(self, request):
return HttpResponse("Article successfully created via POST request.")
Processing HTTP Methods and CSRF Security
In an FBV, developers typically use conditional statements to handle different request types.
# web_app/views.py
from django.http import HttpResponse
def contact_handler(request):
if request.method == 'GET':
return HttpResponse("Displaying the contact form.")
elif request.method == 'POST':
return HttpResponse("Processing the submitted contact form.")
By default, Django enforces CSRF (Cross-Site Request Forgery) protection for POST, PUT, and DELETE requests. This results in a 403 Forbidden error if the request does not include a valid CSRF token.
To bypass this for specific views (common in API development), use the @csrf_exempt decorator:
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
@csrf_exempt
def secure_post_view(request):
if request.method == 'POST':
return HttpResponse("Data received without CSRF validation.")
Alternatively, you can disable the protection globally by removing django.middleware.csrf.CsrfViewMiddleware from the MIDDLEWARE list in settings.py, though this is generally not recommended for production environments.
Returning JSON Responses
In modern web development, views often return structured data rather than HTML. Django provides the JsonResponse class to simplify returning JSON objects.
# web_app/views.py
from django.http import JsonResponse
def api_status_view(request):
payload = {
"status": "online",
"version": "1.0.2",
"message": "服务器运行正常"
}
# Use ensure_ascii=False to prevent encoding issues with non-ASCII characters
return JsonResponse(payload, json_dumps_params={'ensure_ascii': False})
Returning HTML Content
While views can return raw HTML strings, it is standard practice to separate presentation from logic. While the simplest way is passing a string to HttpResponse, production applications utilize Django's template system to render external .html files.
# web_app/views.py
from django.http import HttpResponse
def simple_html_view(request):
raw_html = "<h1>Heading</h1><p>Content goes here.</p>"
return HttpResponse(raw_html)