0

无需修改我的 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'),

]

视图.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)

模板.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”。但是,什么都没有通过。

我将不胜感激任何建议。

4

1 回答 1

0

尝试这个:

path('<int:topic_id>/<int:tutorial_id>', views.topic_tutorial, name='topic_tutorial'),
于 2020-09-07T10:46:59.830 回答