Django - 用户身份验证错误(django.contrib.auth)

时间:2016-04-09 15:13:49

标签: python django django-views django-authentication django-users

关注this tutorial我创建了一个简单的登录页面。但是当我提交登录信息时,会出现以下Python异常:

Traceback (most recent call last): File "/home/jirka/miniconda3/envs/molinf/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/home/jirka/miniconda3/envs/molinf/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jirka/molinf/02-database/moldb/views.py", line 100, in login login(user) File "/home/jirka/molinf/02-database/moldb/views.py", line 94, in login if request.POST: AttributeError: 'User' object has no attribute 'POST'

这是我的代码:

urls.py中的网址: url(r'^login$', moldb.views.login, name='login')

views.py中的登录视图:

def login(request):
    print(request, type(request))
    logout(request)

    if request.POST:
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(user)
            return HttpResponseRedirect('/')

    return render(request, "login.html")

login.html中的登录表单:

<form class="form-horizontal" name="LoginForm" action="{% url 'login' %}" method="post">
    {% csrf_token %}
    {% if next %}
        <input type="hidden" name="next" value="{{ next }}" />
    {% endif %}
    <div class="control-group">
        <label class="control-label" for="username">Username</label>
        <div class="controls">
        <input type="text" id="username" name="username" placeholder="Username">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="password">Password</label>
        <div class="controls">
        <input type="password" name="password" id="password" placeholder="Password">
        </div>
    </div>
    <div class="control-group">
        <div class="controls">
        <button type="submit" class="btn">Login</button>
        </div>
    </div>
</form>

我发现提交表单后print(request, type(request)) views.py的输出正在跟进:

<WSGIRequest: POST '/login'> <class 'django.core.handlers.wsgi.WSGIRequest'>
hanicka <class 'django.contrib.auth.models.User'>

hanicka是经过身份验证的用户的用户名(我通过登录表单发送的用户名)。 很明显异常来自于此,但此视图如何执行两次以及User模型如何到达此处?!

0 个答案:

没有答案