How do I construct a Django reverse/url using query args?

后端 未结 6 485
长发绾君心
长发绾君心 2020-12-13 04:25

I have URLs like http://example.com/depict?smiles=CO&width=200&height=200 (and with several other optional arguments)

My urls.py contains:

ur         


        
6条回答
  •  难免孤独
    2020-12-13 04:45

    I recommend to use builtin django's QueryDict. It also handles lists properly. End automatically escapes some special characters (like =, ?, /, '#'):

    from django.http import QueryDict
    from django.core.urlresolvers import reverse
    
    q = QueryDict('', mutable=True)
    q['some_key'] = 'some_value'
    q.setlist('some_list', [1,2,3])
    '%s?%s' % (reverse('some_view_name'), q.urlencode())
    # '/some_url/?some_list=1&some_list=2&some_list=3&some_key=some_value'
    
    q.appendlist('some_list', 4)
    q['value_with_special_chars'] = 'hello=w#rld?'
    '%s?%s' % (reverse('some_view_name'), q.urlencode())
    # '/some_url/?value_with_special_chars=hello%3Dw%23rld%3F&some_list=1&some_list=2&some_list=3&some_list=4&some_key=some_value'
    

    To use this in templates you will need to create custom template tag

提交回复
热议问题