0

Without having to modify my urls.py, I want to manually add a URL parameter to the end of the {% url %} call in my template. Then, in my view, I want to access that query parameter's value. If lang='fr', open the French template or, if lang='en', open the English template. Here is my code: 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>

I am under the impression that I don't have to add another parameter to my view definition to access the added query parameter "?lang=fr". But, nothing is being passed.

I would appreciate any suggestions.

earl
  • 3
  • 2

1 Answers1

0

try this:

path('<int:topic_id>/<int:tutorial_id>', views.topic_tutorial, name='topic_tutorial'),
Nadhem Maaloul
  • 433
  • 5
  • 11
  • That's what I have already. Will be back in a few hours. – earl Sep 07 '20 at 10:58
  • I removed the trailing '/' at the end of the url – Nadhem Maaloul Sep 07 '20 at 12:38
  • `path('//', views.topic_tutorial, name='topic_tutorial'),` or `path('/', views.topic_tutorial, name='topic_tutorial'),` Generates: UnboundLocalError at /tutorials/6/20/infrastructure-create-bootable-usb/ local variable 'lang' referenced before assignment – earl Sep 07 '20 at 13:25