6👍
Can’t you just check for an overlay_id
and add it to your url?
redirect_url = reverse( ... )
extra_params = '?overlay=%s' % overlay_id if overlay_id else ''
full_redirect_url = '%s%s' % (redirect_url, extra_params)
return HttpResponseRedirect( full_redirect_url )
23👍
You can use a Django QueryDict object:
from django.http import QueryDict
# from scratch
qdict = QueryDict('',mutable=True)
# starting with our existing query params to pass along
qdict = request.GET.copy()
# put in new values via regular dict
qdict.update({'foo':'bar'})
# put it together
full_url = reversed_url + '?' + qdict.urlencode()
And of course you could write a convenience method for it similar to the previous answer.
- Listing Related Fields in Django ModelAdmin
- Is Django Book platform available?
- Django crispy forms: Nesting a formset within a form
- Django: why are Django model fields class attributes?
- How do you actually use a reusable django app in a project?
4👍
Query string args should be properly escaped and not just concatenated!
Building an url with query string by string concatenation is as bad idea as building SQL queries by string concatenation. It is complicated, unelegant and especially dangerous with a user provided (untrusted) input. Unfortunately Django does not offer an easy possibility to pass query parameters to the reverse function.
Python standard urllib however provides the desired query string encoding functionality.
In my application I’ve created a helper function like this:
def url_with_querystring(path, **kwargs):
return path + '?' + urllib.urlencode(kwargs)
Then I call it in the view as follows:
quick_add_order_url = url_with_querystring(reverse(order_add),
responsible=employee.id, scheduled_for=datetime.date.today(),
subject='hello world!')
# http://localhost/myapp/order/add/?responsible=5&
# scheduled_for=2011-03-17&subject=hello+world%21
Please note the proper encoding of special characters like space and exclamation mark!
- How can I specify the parameter for POST requests while using APIView with django-rest-swagger
- Can't pip install mysql-python
3👍
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<id>.+)/(?P<overlay_id>.+)/$', 'update', name="update_foo"),
...
Use reverse like so:
print reverse("update_foo", kwargs={"id":"id_value", "overlay_id": "overlay_id_value"})