Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'))
like image 651
user782400 Avatar asked Apr 16 '14 17:04

user782400


People also ask

What does HttpResponseRedirect do in Django?

HttpResponseRedirect is a subclass of HttpResponse (source code) in the Django web framework that returns the HTTP 302 status code, indicating the URL resource was found but temporarily moved to a different URL. This class is most frequently used as a return object from a Django view.

How do I return HttpResponseRedirect in Django?

Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .


1 Answers

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.

like image 184
Daniel Roseman Avatar answered Oct 11 '22 13:10

Daniel Roseman