162👍
✅
GET parameters have nothing to do with the URL as returned by reverse
. Just add it on at the end:
url = "%s?name=joe" % reverse(viewOne)
84👍
A safer and more flexible way:
import urllib
from django.urls import reverse
def build_url(*args, **kwargs):
get = kwargs.pop('get', {})
url = reverse(*args, **kwargs)
if get:
url += '?' + urllib.urlencode(get)
return url
then you can use build_url
:
url = build_url('view-name', get={'name': 'joe'})
which takes same arguments as reverse
, but provides an extra keyword argument get
where you can put your GET
parameters in it as a dictionary.
- [Django]-Django: How to check if the user left all fields blank (or to initial values)?
- [Django]-How to set and get cookies in Django?
- [Django]-How can I activate the unaccent extension on an already existing model
22👍
This is very similar to Amir’s solution but handles lists as well.
from django.core.urlresolvers import reverse
from django.http import QueryDict
def build_url(*args, **kwargs):
params = kwargs.pop('params', {})
url = reverse(*args, **kwargs)
if not params: return url
qdict = QueryDict('', mutable=True)
for k, v in params.iteritems():
if type(v) is list: qdict.setlist(k, v)
else: qdict[k] = v
return url + '?' + qdict.urlencode()
Example usage:
>>> build_url('member-list', params={'format': 'html', 'sex': ['male', 'female']})
u'/members/?format=html&sex=male&sex=female'
- [Django]-How to resize an ImageField image before saving it in python Django model
- [Django]-Explicitly set MySQL table storage engine using South and Django
- [Django]-Django TextField and CharField is stripping spaces and blank lines
-2👍
Sorry for the delayed correction on this.
While both the answers here handles the required task too well, i think just a simple function to urlencode a dictionary is the most flexible way of doing this:
import urllib
def getify(dic):
st = ''
for K, V in dic.items():
K = urllib.parse.quote(str(K))
if isinstance(V, list):
for v in V:
st += K + '=' + urllib.parse.quote(str(v)) + '&'
else:
st += K + '=' + urllib.parse.quote(str(V)) + '&'
return st.rstrip('&')
- [Django]-Django – Login with Email
- [Django]-How to send a correct authorization header for basic authentication
- [Django]-Create Django model or update if exists
Source:stackexchange.com