django身份验证视图无法正常工作

时间:2014-12-17 14:00:04

标签: django django-views django-authentication

当我尝试登录django项目的登录页面时,会显示消息User with this Username already exists.这里我使用了自己的身份验证视图:

def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is None:
                return HttpResponseRedirect('/logger/bad_login/')
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/')
            else:
                return HttpResponseRedirect('/logger/bad_login/')
    else:
        form = LoginForm()
    return render(request, 'logger/login.html', {'form': form})

后来我找到了django stock auth的观点和表格。但仍想知道为什么我的观点无法正常运作。

我的记录器应用程序的urls.py,它也用于保存用户活动的数据

from django.conf.urls import patterns, include, url

from logger import views


urlpatterns = patterns('',
    url(r'^$', views.logger_view, name='log'),
    url(r'^login/$', views.login_view, name = 'login'),
    url(r'^bad_login/$', views.bad_login_view, name = 'bad_login'),
)

和模板

{% extends "base.html" %}

{% block title %}Login {% endblock title %}

{% block content %}
<form action="/logger/login/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock content %}

LoginForm的

class LoginForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'password')

1 个答案:

答案 0 :(得分:1)

您正在使用ModelForm,这些只会在both the form and the model validation pass

时生效

当您使用用户模型时,您的表单不会在模型级别进行验证,这就是您的视图失败的原因。

如果您更改登录表单,您的视图将按预期工作:

class LoginForm(forms.Form):  # A normal form, not a model form
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

您可能还想修复视图,以便正确显示表单错误,并且您也正确使用该表单:

def login_view(request):
    form = LoginForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user = authenticate(username=username, password=password)
        if user is None:
            return HttpResponseRedirect('/logger/bad_login/')
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect('/')
        else:
            return HttpResponseRedirect('/logger/bad_login/')
    return render(request, 'logger/login.html', {'form': form})