Django模板中如何正确使用链接参数值?
Ah, I see the issue here! You're mixing up URL path parameters with GET query parameters—that's why request.GET isn't working for you. Let me break this down step by step to fix it:
First, Understand the Difference
- GET query parameters live in the part of the URL after
?, likehttp://example.com/?factory=toyota. This is whatrequest.GETis designed to access. - Your URL
http://127.0.0.1:8000/app1/factory/toyota/uses path parameters (toyotais part of the URL path itself), sorequest.GETwon't pick this value up at all.
Step 1: Confirm Your urls.py Configuration
You need to use Django's path converters to capture the factory parameter from the URL path. Here's how your URL pattern should look:
# urls.py from django.urls import path from . import views urlpatterns = [ # ... other URL patterns path('app1/factory/<str:factory>/', views.factory_view, name='factory-detail'), ]
The <str:factory> syntax tells Django to capture the string segment in the path, name it factory, and pass it to your view function.
Step 2: Receive the Parameter in Your View
Update your view function to accept the factory parameter, then pass it to the template via the context:
# views.py from django.shortcuts import render def factory_view(request, factory): # Optional: Add logic here (e.g., query a database using the factory name) return render(request, 'your_template.html', {'factory': factory})
Make sure the parameter name in the view matches exactly what you defined in urls.py (here, it's factory).
Step 3: Use the Parameter in Your Template
Now you can directly access the factory variable in your template—no need for request.GET:
<!-- your_template.html --> <h1>My {{ factory }}</h1>
If you want to conditionally render content based on the parameter's presence, use:
{% if factory %} <h1>My {{ factory }}</h1> {% endif %}
Why Your Previous Attempts Failed
All your request.GET.factory attempts were targeting query parameters (the ?key=value format). Since your URL uses path parameters instead, this approach won't work—Django doesn't store path parameters in request.GET.
内容的提问来源于stack exchange,提问作者Salam Qais

