1π
To the best of my knowledge, Django has no tooling to add querystrings to an URL, but that is not per se a problem, since we can make our own function, for example:
from django.urls import reverse
from django.http.response import HttpResponseRedirect
def redirect_qd(viewname, *args, qd=None, **kwargs):
rev = reverse(viewname, *args, **kwargs)
if qd:
rev = '{}?{}'.format(rev, qd.urlencode())
return HttpResponseRedirect(rev)
Encoding the values is important. Imagine that your group
has as value foo&bar=3
. If you do not encode this properly, then this means that your querystring will later be parsed as two parameters: group
and bar
with group
being foo
and bar
being 3
. This is thus not what you intended. By using the urlencode
, it will result in 'group=foo%26bar%3D3'
, which thus is the intended value.
and then we can use this function like:
from django.http.request import QueryDict
def product_new(request):
group = request.GET.get('group')
if group == None:
product = Product.objects.create()
return redirect('cms:product_list_edit')
else:
product = Product.objects.create(group=group)
qd = QueryDict(mutable=True)
qd.update(group=group)
return redirect_qd('cms:product_list_edit', qd=qd)
If you simply want to pass the entire querystring, you can thus call it with redirect_qd('myview', request.GET)
.
3π
for python3 and above:
def redirect_with_params(viewname, **kwargs):
"""
Redirect a view with params
"""
rev = reverse(viewname)
params = urllib.parse.urlencode(kwargs)
if params:
rev = '{}?{}'.format(rev, params)
return HttpResponseRedirect(rev)
use:
redirect_with_params('main-domain:index', param1='value1', param2='value2')
- [Django]-Django All-Auth django.contrib.auth.backends.ModelBackend invalid syntax
- [Django]-Django DateTimeField input Form
- [Django]-Starting first Django project errors
1π
I found the answer exactly what I wanted.
def product_new(request):
group = request.GET.get('group')
if group == None:
product = Product.objects.create()
return redirect('cms:product_list_edit')
else:
product = Product.objects.create(group=group)
response = redirect('cms:product_list_edit')
response['Location'] += '?group=' + group
return response
- [Django]-Editing existing entries in Django forms
- [Django]-Build When Case query in for loop django
- [Django]-How to redirect to a newly created object in Django without a Generic View's post_save_redirect argument
- [Django]-Django β Is there any way to hide superusers from the user list?
- [Django]-Django, How to pass data object from one template to another template