Alex Rivera | Logout

Django redirect to root from a view

Asked 2011-09-02T14:29:08.927
17

I am creating a django project. However, I have come 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 app 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 am going to the login page, it is opening up as expected. After I submit the form, I get an error that says that it can't find the module urls. After digging around a bit, I noticed that the redirect("/") actually translates into http://localhost/login/ instead of http://localhost/. The same happens in logout, i.e. it tries opening the url http://localhost/logout/ instead of http://localhost/. Basically, when the page opened is http://localhost/login, the redirect('/') adds the / to the end of the current url, and voila - I get a url that I didn't expect - http://localhost/login/. I cannot get it to redirect to the root of the

Edit
Report

1 Answer

5

If you look at the documentation for redirect, there are several things you can pass to the function:

  • A model
  • A view name
  • A URL

In general, I think it's better to redirect to a view name rather than a URL. In your case, assuming your urls.py has an entry that looks something like:

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

I would instead use redirect like this:

redirect('Home.views.index')
answered 2011-09-02T16:40:28.540

Your Answer