49👍
Is possible to add GET variables in a redirect ? (Without having to modifiy my urls.py)
I don’t know of any way to do this without modifying the urls.py
.
I don’t have complains using HttpResponseRedirect(‘/my_long_url/%s/?q=something’, x) instead, but just wondering…
You might want to write a thin wrapper to make this easier. Say, custom_redirect
def custom_redirect(url_name, *args, **kwargs):
from django.core.urlresolvers import reverse
import urllib
url = reverse(url_name, args = args)
params = urllib.urlencode(kwargs)
return HttpResponseRedirect(url + "?%s" % params)
This can then be called from your views. For e.g.
return custom_redirect('url-name', x, q = 'something')
# Should redirect to '/my_long_url/x/?q=something'
130👍
Since redirect just returns an HttpResponseRedirect
object, you could just alter that:
response = redirect('url-name', x)
response['Location'] += '?your=querystring'
return response
- [Django]-Django 1.11 TypeError context must be a dict rather than Context
- [Django]-Filtering dropdown values in django admin
- [Django]-Django admin TabularInline – is there a good way of adding a custom html column?
4👍
We can import urlencode from django.
from django.utils.http import urlencode
get_args_str = urlencode({'q': 'something'})
Or we can just use unparsed get parameters string from starting request
get_args_str = request.META['QUERY_STRING']
HttpResponseRedirect('%s?%s' % (url, get_args_str))
- [Django]-What is the Simplest Possible Payment Gateway to Implement? (using Django)
- [Django]-Django + Ajax
- [Django]-What is the most efficient way to store a list in the Django models?
2👍
I think it’s worth noting that Django’s RedirectView
class has a built-in class attribute query_string
which can be overridden or passed to as_view
. If set to True
, query_string
will preserve the query string in the redirect. For example, you could put the following in urls.py
:
path('example-redirect/',
RedirectView.as_view(url='https://example.com', query_string=True),
name='example_redirect')
- [Django]-How to receive json data using HTTP POST request in Django 1.6?
- [Django]-Django: is there a way to count SQL queries from an unit test?
- [Django]-Mixin common fields between serializers in Django Rest Framework