You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 ?, like http://example.com/?factory=toyota. This is what request.GET is designed to access.
  • Your URL http://127.0.0.1:8000/app1/factory/toyota/ uses path parameters (toyota is part of the URL path itself), so request.GET won'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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:13:05