Django render redirect to page with changing url

10,695

Currently you are rendering the 'home.html template, instead of redirecting the user to the homepage.

If you want to redirect then you should return an HttpResponseRedirect response, or use the redirect shortcut.

from django.shortcuts import redirect

def logout(request):
    ...
    return redirect('/')
Share:
10,695
Sarthak Rohilla
Author by

Sarthak Rohilla

Updated on June 04, 2022

Comments

  • Sarthak Rohilla
    Sarthak Rohilla almost 2 years

    I am creating a custom login for my django application and problem occurs when i click logout on template I programmed it so it go to index page but the url in the browser remains http://127.0.0.1:8000/logout/ even reaching index page. I want it to become http://127.0.0.1:8000/ .

    views.py

    def logout(request):
        try:
            del request.session['uid']
            return render(request, 'home.html')
        except:
            pass
        return render(request, 'home.html')
    
    def home_page(request):
        return render(request, 'home.html')
    

    template

     <p>
        Publisher Dashboard, Welcome {{ user.name }}.
        <a href="{% url 'logout' %}" class="btn btn-primary">Logout</a>
    </p>
    

    urls.py

    from django.conf.urls import url
    from django.contrib import admin
    from mainapp import views
    
    urlpatterns = [
    url(r'^$', views.home_page, name='homepage'),
    url(r'^registration/$', views.signup_user, name='signup_user'),
    ....
    url(r'^logout/$', views.logout, name='logout'),
    ]
    
    • Alasdair
      Alasdair almost 7 years
      Django has a built in authentication system. You should use this if at all possible, rather than rolling your own system that uses session['uid'].
  • Sarthak Rohilla
    Sarthak Rohilla almost 7 years
    can i use redirect() to send some value from views.py to template as redirect('/', { 'user': user }) ? @Alasdair
  • Alasdair
    Alasdair almost 7 years
    No. See this answer.
  • Sarthak Rohilla
    Sarthak Rohilla almost 7 years
    Thanks for help. @Alasdair