Django:HttpResponseRedirect无效

时间:2013-10-29 00:04:30

标签: python django authentication redirect login

我是Python / Django的新手,整体编程。我需要HttpResponseRedirect的帮助,因为它不能在我的登录视图中工作。它可以从我的主视图文件中工作,但不是我想要的方式。

我没有重定向到所需的页面('/'),而只是在同一页面上看到它:

  

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

用户实际登录但保持在同一页面上。因此,如果我手动转到所需的页面,我会看到我已登录。

以下是相关的代码段。我到处都在使用自己的观点。我希望通过这种方式练习和更好地理解。

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 - 简单表单

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

我遵循了关于这个的Django书籍教程,根据它,一切都应该工作得很好。正如你所看到的,我也尝试在我的表单中使用“下一个”隐藏字段,这也不起作用。任何帮助,将不胜感激。我想知道我在这里失踪了什么。谢谢!

1 个答案:

答案 0 :(得分:7)

你在html中看到“Content-Type:text / html; charset = utf-8 Location:/”的原因是因为你返回一个HttpResponse对象作为你要在响应中呈现的上下文数据的一部分而不是这是实际的反应。你注销看起来也有点奇怪。但要与你现在拥有的东西合作:

更改您的views.py

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

然后更改LoginView.login中的视图以始终返回所需的Response对象(重定向或要呈现的页面)

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