Django url parameter and reverse URL

11,984

Solution 1

You can pass the relevant arguments in url tag, if your url (in urls.py) has any capturing group.

url(r'^set/(?P<the_city>\w+)/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'),

Then in template:

<a tabindex="-1" href="{% url ciudad the_city='gye' %}">Guayaquil</a>

Solution 2

Check out captured parameters. Something like this might work:

url(r'^set/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'),
url(r'^set/(?P<the_city>\w+)/$', views.selectCity, name='ciudad'),
Share:
11,984
edu222
Author by

edu222

FrontEnd Development Engineer

Updated on June 04, 2022

Comments

  • edu222
    edu222 almost 2 years

    I have a view that looks like this:

    def selectCity(request, the_city):
        request.session["ciudad"] = the_city
        city = request.session["ciudad"]
        return HttpResponse('Ciudad has been set' + ": " + city)
    

    And a URL that looks like this:

    url(r'^set/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'),
    

    Now when I visit /set/ I get the appropriate response with the session variable set from the value on the dict in the url {'the_city': 'gye'}

    Now, what I would like to do is modify my program so that I can call the 'ciudad' url from a different template (index.html) and set the appropriate session variable. So I would call it using reverse URL matching with an additional argument doing something like this:

      <div class="modal-body">
          <a tabindex="-1" href="{% url ciudad 'the_city':'uio' %}">Quito</a>
          <br/>
          <a tabindex="-1" href="{% url ciudad 'the_city':'gye' %}">Guayaquil</a>
      </div>
    

    I have tried to modify the url and the views and the reverse url call in various ways to try to get this to work but, I can't seem to figure it out. I would really appreciate some pointers.

  • edu222
    edu222 over 11 years
    Yup, this is perfect,thanks! A quick question, what does that \w+ part or the regular expression do?
  • Aamir Rind
    Aamir Rind over 11 years
    Please see here, \w+ means it matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_]