简体   繁体   中英

Django redirect to root from a view

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, ie 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 site using the redirect.

Please help me out with this and if possible also explain the cause of this irrational behavior of Django

I am using Django 3.1. This is what I do to achieve this:

in urls.py

from django.shortcuts import redirect

urlpatterns = [
    path('', lambda req: redirect('/myapp/')),
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls'))
]

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')

Also complementing Ken Cloud answer, if you have named urls you can just call the url name:

from django.shortcuts import redirect

urlpatterns = [
    path('app/', include('myapp.urls'), name='app')
    path('', lambda req: redirect('app')),
    path('admin/', admin.site.urls),
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM