Django redirects to root from view

I am creating a django project. However, I came across a small hiccup. My urls.py looks like this:

url(r'^login/(?P<nextLoc>)$', 'Home.views.login'), url(r'^logout/$', 'Home.views.logout'), 

My views.py in the Home application is as follows:

 def login(request,nextLoc): if request.method == "POST": form = AuthenticationForm(request.POST) user=auth.authenticate(username=request.POST['username'],password=request.POST['password']) if user is not None: if user.is_active: auth.login(request, user) return redirect(nextLoc) else: error='This account has been disabled by the administrator. Contact the administrator for enabling the said account' else: error='The username/password pair is incorrect. Check your credentials and try again.' else: if request.user.is_authenticated(): return redirect("/profile/") form = AuthenticationForm() error='' return render_to_response('login.html',{'FORM':form,'ERROR':error},context_instance=RequestContext(request)) def logout(request): auth.logout(request) return redirect('/') 

Now, when I go to the login page, it opens as expected. After I submit the form, I get an error message stating that it cannot find the module URLs. After working a bit, I noticed that the redirect ("/") actually converts to http://localhost/login/ instead of http://localhost/ . The same thing happens when you exit the system, i.e. Attempts to open the URL http://localhost/logout/ instead of http://localhost/ . Basically, when the open page is http://localhost/login , redirect('/') adds / to the end of the current url, and voila - I get a url that I did not expect - http://localhost/login/ . I cannot get it to redirect to the root of the site using redirection.

Please help me with this and, if possible, also explain the reason for this irrational behavior of Django

+6
source share
1 answer

If you look at the documentation for redirection , you can go to the function:

  • Model
  • View name
  • URL

In general, I think it's better to redirect the view name, not the URL. In your case, if your urls.py has an entry that looks something like this:

 url(r'^$', 'Home.views.index'), 

Instead, I would use a redirect like this:

 redirect('Home.views.index') 
+3
source

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


All Articles