Django redirect using reverse() to a URL that relies on query strings

前端 未结 4 1801
Happy的楠姐
Happy的楠姐 2021-01-04 07:05

I\'m writing a django application with a URL like \'http://localhost/entity/id/?overlay=other_id\'. Where id is the primary key of the particular entity and overlay is an o

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 07:38

    You shouldn't generate the url string yourself. Given your urls.py you can use reverse like so:

    from django.core.urlresolvers import reverse
    print reverse('view_function_name', kwargs={"id":"id_value", "overlay_id": "overlay_id_value"})
    
    # or to pass view function arguments as an array:
    print reverse('view_function_name', args=("id_value","overlay_id_value",))
    

    If you use named url patterns, which are great for disconnecting your view functions from url identifiers:

    # urls.py
    ...
    (r'^update/(?P.+)/(?P.+)/$', 'update', name="update_foo"),
    ...
    

    Use reverse like so:

    print reverse("update_foo", kwargs={"id":"id_value", "overlay_id": "overlay_id_value"})
    

提交回复
热议问题