杰瑞科技汇

Django视图如何高效处理请求?

Of course! Let's break down Django views from the ground up. This is one of the most fundamental concepts in Django.

Django视图如何高效处理请求?-图1
(图片来源网络,侵删)

What is a View?

In the Model-View-Template (MVT) architectural pattern used by Django:

  • Model: Represents your data structure (e.g., database tables). It's the "M".
  • Template: The presentation layer (the HTML files). It's the "T".
  • View: The business logic. It's the "V". It receives a web request, interacts with the Model if needed, and then decides which Template to return as a response.

A view is simply a Python function (or a class) that takes a web request and returns a web response.


The Simplest Possible View

A view doesn't have to be complex. Here's the most basic view you can write. It doesn't even need a model or a template.

Let's say you have a file myapp/views.py.

Django视图如何高效处理请求?-图2
(图片来源网络,侵删)
# myapp/views.py
from django.http import HttpResponse
def welcome(request):
    """
    A simple view that returns a plain text HTTP response.
    """
    return HttpResponse("Hello, Django! Welcome to your first view.")

Explanation:

  1. from django.http import HttpResponse: We import the HttpResponse class, which is used to generate an HTTP response. This is the most basic type of response.
  2. def welcome(request):: This defines a Python function named welcome.
    • request: Every view function must take at least one argument, conventionally named request. This request object contains all the information about the current web request, such as the URL path, headers, GET/POST data, etc. It's an instance of a HttpRequest object.
  3. return HttpResponse(...): The view must return an HttpResponse object. In this case, we're returning a simple string. Django will automatically set the correct Content-Type header.

Making it Accessible via a URL

A view is useless if the web server doesn't know which URL should trigger it. This is where the urls.py file comes in.

  1. Create a URL configuration for your app: In your app's directory (myapp/), create a file named urls.py if it doesn't exist.

    # myapp/urls.py
    from django.urls import path
    from . import views  # Import the views from the current app
    urlpatterns = [
        # When a user visits the root of this app (e.g., /myapp/),
        # call the 'welcome' view.
        path('', views.welcome, name='welcome'),
    ]
  2. Include your app's URLs in the main project's urls.py: Django needs to know that URLs starting with /myapp/ should be handled by your app's urls.py.

    Django视图如何高效处理请求?-图3
    (图片来源网络,侵删)
    # your_project/urls.py
    from django.contrib import admin
    from django.urls import path, include  # Make sure to import 'include'
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('myapp/', include('myapp.urls')), # Include the app's URLs
    ]

Now, if you run your Django server (python manage.py runserver) and navigate to http://127.0.0.1:8000/myapp/, you will see "Hello, Django! Welcome to your first view."


Dynamic Views: Using URL Parameters

Views become powerful when they can handle dynamic parts of a URL, like a user's ID or a blog post's slug.

Let's create a view that displays a profile for a specific user based on their ID.

Step 1: Update myapp/urls.py

We'll use angle brackets < > to define a URL parameter. Django will capture the value and pass it to the view as a keyword argument.

# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
    # ... other urls
    path('profile/<int:user_id>/', views.user_profile, name='user_profile'),
]
  • <int:user_id>: This part is special.
    • int:: This is a converter. It tells Django to convert the captured part of the URL into an integer.
    • user_id: This is the name of the keyword argument that will be passed to the view function.

Step 2: Update myapp/views.py

The view function must now accept this new keyword argument.

# myapp/views.py
from django.http import HttpResponse
# ... other views
def user_profile(request, user_id):
    """
    Displays a user's profile based on their ID.
    """
    # In a real app, you would query the database here
    # user = User.objects.get(pk=user_id)
    # return HttpResponse(f"Profile for {user.username}")
    # For this example, we just return the ID
    return HttpResponse(f"You are viewing the profile for User ID: {user_id}")

Now, if you navigate to http://127.0.0.1:8000/myapp/profile/123/, the output will be You are viewing the profile for User ID: 123.


Using Templates to Render HTML

Hardcoding HTML in a view is not a good practice. Django's template system allows you to separate logic from presentation.

Step 1: Create the Template

  1. Inside your app directory (myapp/), create a folder named templates.

  2. Inside myapp/templates/, create another folder with the same name as your app (myapp).

  3. Finally, create an HTML file inside that, e.g., myapp/templates/myapp/user_profile.html.

    <!-- myapp/templates/myapp/user_profile.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>User Profile</title>
    </head>
    <body>
        <h1>User Profile</h1>
        <p>You are viewing the profile for User ID: <strong>{{ user_id }}</strong></p>
        <p>This page was generated on: {{ current_time }}</p>
    </body>
    </html>

Step 2: Update the View to Use the Template

We need to import render, which is a shortcut that combines a template and a context dictionary to return an HttpResponse object.

# myapp/views.py
from django.shortcuts import render # Import render
from django.http import HttpResponse
from django.utils import timezone # To get the current time
# ... other views
def user_profile(request, user_id):
    """
    Displays a user's profile using a template.
    """
    # The 'context' is a dictionary that passes data to the template.
    # The keys in the dictionary become variables in the template.
    context = {
        'user_id': user_id,
        'current_time': timezone.now(),
    }
    # The 'render' function takes:
    # 1. The request object
    # 2. The path to the template (relative to the 'templates' folder)
    # 3. The context dictionary
    return render(request, 'myapp/user_profile.html', context)

Now, when you visit /myapp/profile/123/, Django will find the template, fill in the variables ({{ user_id }} and {{ current_time }}), and send the final HTML to the browser.


Handling Different HTTP Methods (GET, POST)

A single URL can be accessed with different HTTP methods. A GET request is for retrieving data, while a POST request is for submitting data (like a form).

Here’s how you can handle both in one view.

# myapp/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
def contact_form(request):
    """
    Handles both displaying a form (GET) and processing form data (POST).
    """
    if request.method == 'POST':
        # This block runs when the form is submitted
        name = request.POST.get('name')
        email = request.POST.get('email')
        if name and email:
            # In a real app, you would save this to the database
            return HttpResponse(f"Thank you, {name}! We have received your message at {email}.")
        else:
            return HttpResponse("Error: Please fill in all fields.")
    # This block runs when the page is first requested (GET)
    return render(request, 'myapp/contact_form.html')

The Template (myapp/templates/myapp/contact_form.html):

<!DOCTYPE html>
<html lang="en">
<head>Contact Us</title>
</head>
<body>
    <h1>Contact Us</h1>
    <form method="post">
        {% csrf_token %} <!-- IMPORTANT: Django's security feature for forms -->
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name"><br><br>
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Summary of Key Concepts

Concept Description Example
View Function A Python function that takes a request and returns a response. def my_view(request):
HttpResponse The most basic response object, used to return plain text or HTML. return HttpResponse("Hello")
render() A shortcut that loads a template, fills it with context, and returns an HttpResponse. return render(request, 'template.html', context)
URL Parameters Captured parts of a URL passed to the view as arguments. path('user/<int:id>/', views.user_detail)
Context A Python dictionary passed to a template to make data available in the HTML. context = {'name': 'Alice'}
HTTP Methods Views can check request.method to handle GET, POST, etc., differently. if request.method == 'POST':
redirect() A helper function to send the user to a different URL. return redirect('home')
分享:
扫描分享到社交APP
上一篇
下一篇