Django: HttpResponseRedirect not passing RequestContext ()?

Basically, I am trying to redirect people who are not logged in to the login page.

I am currently using:

return render_to_response('login.html', context_instance=RequestContext(request)) 

But that leaves the URL on the main page. I would like it to redirect to / accounts / login /, but when I use

 return HttpResponseRedirect('/accounts/login/') 

I get an error

 Key 'username' not found in <QueryDict: {}> 

I understand what I need to have

 context_instance=RequestContext(request)) 

Do I need to have the correct redirect and still pass the RequestContext?

+4
source share
1 answer

RequestContext is only used to pass values ​​to the template engine when rendering the template. The type of destination should not depend on the RequestContext from the original type, it should be able to generate its own RequestContext.

However, there are situations where you need to pass values ​​between representations like this. In these situations, you can use the querystring values ​​for this. For instance...

 def originating_view(request, *args, **kwargs): return HttpResponseRedirect('/accounts/login/?username=%s&next=%s' % (username, request.path) def destination_view(request, *args, **kwargs): # Get the username from the querystring username = request.GET.get('username', None) next = request.GET.get('next', '/') if username: # ... 

(Please note that I assume that you want to save the username so that it is pre-populated in the login form. If you are actually logging in, you will want to use POST instead so that the username and password are not written in text form URL).

+5
source

Source: https://habr.com/ru/post/1308091/


All Articles