Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 884
Rohit Mitra Avatar asked Sep 02 '11 14:09

Rohit Mitra


People also ask

How do I redirect in Django?

Django Redirects: A Super Simple Example 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/ .

What is the difference between HttpResponseRedirect and redirect in Django?

There is a difference between the two: In the case of HttpResponseRedirect the first argument can only be a url . redirect which will ultimately return a HttpResponseRedirect can accept a model , view , or url as it's "to" argument. So it is a little more flexible in what it can "redirect" to.

What is reverse redirect in Django?

the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. Syntax: Web development, programming languages, Software testing & others. from django.urls import reverse.

How do I change the root URL in Django?

A quick way is to include the projects url patterns at the new path. At the bottom of the main urls.py include the base_patterns at the new path. Save this answer.


1 Answers

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'))
]
like image 106
Ken Cloud Avatar answered Oct 23 '22 16:10

Ken Cloud