Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Django Views: Functions, Classes, and Request Handling

Tech 3

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 parameters
  • request.POST: Dictionary-like object containing POST form data
  • request.body: Raw request body (useful for non-form data like JSON)
  • request.path / request.path_info: URL path component
  • request.get_full_path(): URL path with query string
  • request.method: HTTP method (e.g., "GET", "POST")
  • request.encoding: Character encoding of submitted data
  • request.META: Dictionary containing HTTP headers
  • request.FILES: Dictionary containing uploaded files
  • request.COOKIES: Dictionary containing cookies
  • request.session: Session datta dictionary

Important notes:

  • Use request.method == "POST" instead of checking request.POST to 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.FILES when the form uses enctype="multipart/form-data"
Tags: Django

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.