user782400
user782400

Reputation: 1737

Pass arguments using the HttpResponseRedirect in Django

I am trying to pass some information to my index page(index.html) from views.py. One passed, I need to access it in the index page. I have tried googling it, but it wasn't clear to me. Any help would be appreciated. I have attached below what I have tried.

Below I want to access the value "bar" in the index page. How can I do that ?

def tempLogin(request):
   username = request.POST['username']
   password = request.POST['password']
   user = authenticate(username=username, password=password)
   if user is not None:
       if user.is_active:
           login(request, user)
           return HttpResponseRedirect(reverse('index',foo='bar'))
       else:
           return HttpResponseRedirect(reverse('index'))
   else:
       return HttpResponseRedirect(reverse('index'))

Upvotes: 5

Views: 12660

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 600059

I see this question quite a lot, and it betrays a lack of understanding of what HttpResponseRedirect does. All it does is tell the browser to go and fetch another URL: so the only parameters you can pass to it are those that would be expected by that other URL pattern. If your index URL has an optional space for you to put a name value, then you can pass it. Otherwise, you'll need to do it some other way: perhaps in the session.

Upvotes: 12

xyres
xyres

Reputation: 21844

You can't do this using HttpResponse or HttpResponseRedirect. You'd have to use render or render_to_response. Somewhat like below:

from django.shortcuts import render

def templogin(request):
    # Do all your processings here ...
    return render(request, 'index.html', {'bar': bar})

The first argument passed to render is always request. Second argument is the name of the template. In your case, it is index.html. And the third argument is a dictionary i.e the variables to add to template context. In your case it is bar.

Here's more about render on Django docs.

And then in your template, you can access the bar variable somewhat as below:

<h1> {{ bar }} </h1>

or

<span> Hello, {{ bar }}! </span>

Django will automatically replace {{ bar }} with it's value.

Upvotes: 4

Related Questions