Django:request.user.is_authenticated()在Template中返回true,但在View中返回false

时间:2016-10-02 22:08:07

标签: django

我正在使用Django表单和其他包编写一个简单的登录/注销表单。 在我的注销中,查看这是我所拥有的,但看起来request.user.is_authenticated()总是返回false,因为它总是转到else语句。

def logout_view(request):
    try:
        if request.user.is_authenticated():
            logout(request)
            return HttpResponseRedirect("registration:login")
        else:
            return HttpResponse("User was never signed in")
    except:
        return HttpResponse("User was never logged in")

但是,在我的template.py中,request.user.is_authenticated正常工作。它返回“我已登录”,那么为什么我的视图返回false?谢谢你的帮助:D

<h1>Home Page</h1>
{{ user.username }}


<form action="{% url 'registration:logout'%}" method="POST">
    {% csrf_token %}
    {% if request.user.is_authenticated %}
      <p>I'm logged in</p>
    {% else %}
      <p>I am anonymous</p>
    {% endif %}
    <input type="submit" value="Log out"/>
</form>

另外,这是我的urls.py

from . import views

app_name = 'registration'


urlpatterns = [
    url(r'^test', views.login, name='test'),
    url(r'^login/', views.login_view, name='login'),
    url(r'^signup/(?P<user_id>[0-9]+)/$',views.signup,name='signup'),
    url(r'^logout/',views.logout_view,name='logout'),
    url(r'^update/(?P<userNet_id>[0-9]+)?',views.updateProfile,name='update'),
    url(r'^home/(?P<userNet_id>[0-9]+)?',views.homePage,name='home'),
]

0 个答案:

没有答案