【问题标题】:Django 2 Adding URL Parameter after {% url %} call in templateDjango 2 在模板中调用 {% url %} 后添加 URL 参数
【发布时间】:2020-12-25 18:14:20
【问题描述】:

无需修改我的 urls.py,我想手动将 URL 参数添加到模板中 {% url %} 调用的末尾。 然后,在我看来,我想访问该查询参数的值。如果 lang='fr',打开法语模板,或者,如果 lang='en',打开英文模板。 这是我的代码: urls.py

urlpatterns = [
path('<int:topic_id>/', views.tutorials, name='tutorials'),
path('<int:topic_id>/<int:tutorial_id>/', views.topic_tutorial, name='topic_tutorial'),
path('<int:topic_id>/<int:tutorial_id>/<slug:slug>/', views.topic_tutorial, name='topic_tutorial_keywords'),

]

views.py

def topic_tutorial(request, topic_id, tutorial_id, slug=None):
"""Show specific Tutorial by topic"""
# NOTE: nothing is returned 
if (request.GET.get('lang')):
    lang = request.GET.get('lang')

topics = Topic.objects.all()
tutorial = Tutorial.objects.get(topic__id=topic_id, id=tutorial_id)

if request.path != tutorial.get_absolute_url():
    return redirect(tutorial, permanent=True)
# renaming topic to avoid spaces
name = tutorial.topic.text.lower()
if (' ' in name):
    name = "_".join( name.split() )

# renaming tutorial to avoid spaces
tut_name = tutorial.text.lower()
if (' ' in tut_name):
    tut_name = "_".join( tut_name.split() )

# lang always empty
if (lang == 'fr'):
    file = name + "-" + tut_name + "_fr.html"
else:    
    file = name + "-" + tut_name + ".html"

path = 'tutorials/' + file
context = {'tutorial': tutorial,'topics': topics,'file':file}
return render(request, path, context)

template.html

<div class="card-body">
          <h5 class="card-title">{{ tut.text }}</h5>
          <p class="card-text">{{ tut.summary }}</p>
          <p class="card-text">
            <a href="{% url 'topic_tutorial' tut.topic.id tut.id %}?lang=en">English</a> | 
            <a href="{% url 'topic_tutorial' tut.topic.id tut.id %}?lang=fr">French</a></p>
        </div>

我的印象是我不必在视图定义中添加另一个参数来访问添加的查询参数“?lang=fr”。但是,什么都没有通过。

如果有任何建议,我将不胜感激。

【问题讨论】:

    标签: django django-request


    【解决方案1】:

    试试这个:

    path('<int:topic_id>/<int:tutorial_id>', views.topic_tutorial, name='topic_tutorial'),
    

    【讨论】:

    • 这就是我已经拥有的。几小时后回来。
    • 我删除了网址末尾的尾随'/'
    • path('&lt;int:topic_id&gt;/&lt;int:tutorial_id&gt;/', views.topic_tutorial, name='topic_tutorial'),path('&lt;int:topic_id&gt;/&lt;int:tutorial_id&gt;', views.topic_tutorial, name='topic_tutorial'), 生成:UnboundLocalError at /tutorials/6/20/infrastructure-create-bootable-usb/ 分配前引用的局部变量“lang”
    猜你喜欢
    • 2014-10-10
    • 2013-03-02
    • 2016-01-20
    • 2021-05-17
    • 1970-01-01
    • 2015-04-17
    • 2020-01-02
    • 2017-08-11
    • 2019-01-03
    相关资源
    最近更新 更多