Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: HttpResponseRedirect not working

I'm new at Python/Django and programming overall. I need help with HttpResponseRedirect as it's not working from my Login view. It does work from my main Views file but not the way I want it.

Instead of redirecting to the desired page ('/'), I only see this on the same page:

Content-Type: text/html; charset=utf-8 Location: /

The user actually gets logged in but stay on the same page. So, if I manually go to the desired page, I will see that I am logged in.

Here are the relevant pieces of code. I am using my own views everywhere. I'd like it this way for practice and better understanding.

Urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from backend import settings
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^login/', 'backend.views.login', name = 'login'),
    url(r'^logout/', 'backend.views.logout', name = 'logout'),
    url(r'^$', 'backend.views.dash', name = 'dash'),
    url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

Views.py

from dashboard.dashviews import left, right, topright
from authentication.authviews import LoginView, LogoutView
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required(login_url='/login/')
def dash(request):
    return render(request, 'dash_template.html', 
        {'left': left.dash_left(request), 
         'right': right.dash_right(), 
        'topright': topright.top_right(request)})

def login(request):
    if not request.user.is_authenticated():
        return render(request, 'login.html', {'login': LoginView.login_view(request)})
    else:
        return HttpResponseRedirect('/')

def logout(request):
    return render(request, 'logout.html', {'logout': LogoutView.logout_view(request)}) and HttpResponseRedirect('/login/')

LoginView.py

from django.contrib import auth
from django.http import HttpResponseRedirect

def login_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        # Correct password, and the user is marked "active"
        auth.login(request, user)
        # Redirect to dashboard
        return HttpResponseRedirect('/')
    else:
    # Show a message     
        return 'Please enter your username and password below.'

login.html - simple form

<center>

<p>{{ login }}</p>

  {% if form.errors %}
    <p class="error">Sorry, that's not a valid username or password</p>
  {% endif %}


  <form action="./" method="post">
        <table border="0">
    <tr>
    <td>
    <label for="username">Username:</label>
    </td>
    <td>
    <input type="text" name="username" value="" id="username">
    </td>
    </tr>
    <tr>
    <td>
    <label for="password">Password:</label>
    </td>
    <td>
    <input type="password" name="password" value="" id="password">
    </td>
    </tr>
    </table>
    <input type="submit" value="login" />
    <input type="hidden" name="next" value="/" />
    {% csrf_token %}
  </form>

</center>

I followed the Django book tutorial on this and according to it, it all should work just fine. As you can see I've also tried using the 'next' hidden field in my form which doesn’t work either. Any help would be appreciated. I wonder what I'm missing here. Thanks!

like image 618
Yuri Yerofeyev Avatar asked Oct 29 '13 00:10

Yuri Yerofeyev


1 Answers

The reason why your seeing "Content-Type: text/html; charset=utf-8 Location: /" in your html is because you return a HttpResponse object as part of your context data to be rendered in the response instead of it being the actual response. You're logout looks also a little weird. But to work with what you currently have:

Change your views.py

if not request.user.is_authenticated():
    # LoginView.login_view will return a HttpResponse object
    return LoginView.login_view(request)
else:
    ...

Then change the view in your LoginView.login to always return the Response object you want (the redirect or the page you want rendered)

def login_view(request):
    # if the request method is POST the process the POST values otherwise just render the page
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            # Correct password, and the user is marked "active"
            auth.login(request, user)
            # Redirect to dashboard
           return HttpResponseRedirect('/')
        else:
            # Show a message     
            err_msg = 'Please enter your username and password below.'
    return render(request, 'login.html', {'login': err_msg})
like image 71
toad013 Avatar answered Oct 07 '22 19:10

toad013