Reputation: 3848
Is it possible to send data while to redirecting to another view?
For example:-
def social_user():
//do something here
return redirect('name of the view',{'variable':'value'})
or any other alternative to exchange data between a function and view function.
Upvotes: 0
Views: 1849
Reputation: 3386
First Solution::
If you have access to the request variable in social_user
, you can simply make use of sessions. Sessions are the best way to transfer data between 2 views.
def social_user(request):
request.session['variable'] = 'value'
return redirect('name of the view')
Then inside your view, you can access this variable using request.session.get('variable')
Second Solution::
In case you can't set session variables, send them as query parameters.
def social_user():
//do something here
return redirect("your_view/?variable=value")
Upvotes: 1
Reputation: 12090
There are two ways to send data to the resulting destination, but first you should understand how redirects work.
When the server redirects, it just sets the Location
header telling the browser which page to fetch next.
Location: /foo.html
Since the body is completely ignored even if present, you must somehow pass data via the HTTP headers.
The easiest way is to use query (GET) parameters which you can then read from the destination page:
Location: /foo.html?username=bob
The downside is that the user can easily see and modify this value.
The session, which is determined by cookies, is another place to store temporary data. But this has several downsides:
It is not tied to any request, so you all consequent request will have access to the data until you delete it.
It doesn't work if the user has disabled cookies. On the other hand query parameters always work.
If you choose the first option, you may need to write some of your own code since Django doesn't seem to offer a convenient method to do this (someone correct me if I'm wrong). Here's a sample function that wraps the functionality:
def redirect_with_query(path, query=None, *args, **kwargs):
if query is None:
query = {}
url = resolve_url(path, *args, **kwargs)
if len(query):
q_dict = QueryDict(mutable=True)
q_dict.update(query)
url += '?' + q_dict.urlencode()
return HttpResponseRedirect(url)
Upvotes: 1
Reputation: 10256
Use render()
and pass the variable via context
:
def social_user(request)
// do something here
return render(request, template_name='template.html', context={'variable': 'value'})
Upvotes: 0
Reputation: 257
Upvotes: 0