无需修改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”。但是,什么都没有通过。
任何建议,我将不胜感激。
答案 0 :(得分:0)
尝试一下:
path('<int:topic_id>/<int:tutorial_id>', views.topic_tutorial, name='topic_tutorial'),