如何解决在模板中{%url%}调用之后,Django 2添加URL参数
无需修改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>/',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”。但是,什么都没有通过。
任何建议,我将不胜感激。
解决方法
尝试一下:
path('<int:topic_id>/<int:tutorial_id>',views.topic_tutorial,name='topic_tutorial'),
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。