Django return redirect() with parameters
Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:
/link/mybackend/?field1=value1&field2=value2&field3=value3
and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET
.
So your urlconf would be:
url(r'^link/(?P<backend>\w+?)/$', my_function)
and the view would look like:
def my_function(request, backend):
data = request.GET
and the reverse would be (after importing urllib
):
return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
Edited after comment
The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.
If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.
That said, if all you want to do is store the data, then just put it in the session:
request.session['temp_data'] = form.cleaned_data
Django: redirect to view with parameters
Try using this instead
from django.urls import reverse
return redirect(reverse('profile', kwargs={"user_id": userid}))
Or this:
return redirect('app_1:profile', user_id=userid)
Django redirect() with additional parameters
If you don't want to pass the email via the URL in the redirect, it may be easiest to store it in the session.
def first(request):
request.session['email'] = 'some_email'
return redirect('confirm')
def confirm(request):
return render(request, 'template.html', {'email': request.session['email']})
How to redirect with a get parameter in django view?
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)
.
django redirect() with parameters
redirect
is merely a wrapper around HttpResponseRedirect
that automatically calls reverse
for you to create the URL to redirect to. As a result, the parameters you pass to it, aren't arbitrary, they must be same you would pass to reverse
and, specifically, only those required to create the URL.
Many people seem to have troubles understanding that data can't just be arbitrarily passed to a view. HTTP is a stateless protocol: each request exists on it's own, as if user had never been to any other page of the site. The concept of a session was created to provide a sense of "state" to a cohesive unit such as a site. With sessions, data is stored in some form of persistent storage and a "key" to look up that data is given to the client (typically the user's browser). On the next page load, the client sends the key back to the server, and the server uses it to look up the data to give the appearance of state.
As a result, if you need data from one view available in another, you need to add it to the session, do your redirect, and look up the data in the session from the next view.
Return redirect wont pass parameters
With redirect
, you can use the name of the path, and then pass positional and/or keyword parameter.
Another problem is that you use .filter(…)
[Django-doc], this thus means that you retrieve a collection of objects (that can contain zero, one, or more last_boards
. YOu should retrieve only one, so:
def index(request):
usuario = request.user
if request.method == 'GET' and usuario.is_authenticated:
usr = get_object_or_404(Usuario, user=usuario.id)
# name of the view ↓
return redirect('board', id=usr.last_board)
return render(request, "index.html")
Related Topics
Pythonic Way to Check If a File Exists
Python Pandas: How to Specify Data Types When Reading an Excel File
What's the Difference Between _Builtin_ and _Builtins_
Can Elementtree Be Told to Preserve the Order of Attributes
Python's JSON Module, Converts Int Dictionary Keys to Strings
Multiple Models in a Single Django Modelform
Checking If All Elements in a List Are Unique
Advanced Nested List Comprehension Syntax
Debugging (Displaying) SQL Command Sent to the Db by SQLalchemy
Python: Platform Independent Way to Modify Path Environment Variable
Downloading with Chrome Headless and Selenium
Inheritance of Private and Protected Methods in Python
How to Set Env Variable in Jupyter Notebook
The Problem with Installing Pil Using Virtualenv or Buildout
How to Make Scipy.Interpolate Give an Extrapolated Result Beyond the Input Range