Django ValidationError只显示一个错误

时间:2017-06-25 15:57:46

标签: python django

我正在尝试创建一个Django登录屏幕,在用户例如没有输入正确的密码时显示错误。 但我收到的唯一错误是"这个用户不存在!"如何才能显示其他错误消息?我的代码有什么问题?

forms.py

class UserLogInForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        #if username and password:
        # user = get_user_model()
        user = authenticate(username=username, password= password)
        # user = authenticate(username=username)
        if not user:
            raise forms.ValidationError("This user does not exist!")
        if not user.check_password(password):
            raise forms.ValidationError("Incorrect password!")
        if not user.is_active:
            raise forms.ValidationError("This user is no longer active.")

        return super(UserLogInForm, self).clean(*args, **kwargs)

views.py

def login_view(request):
    title = "Login"
    form = UserLogInForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(username=username, password=password)
        login(request, user)
        return redirect('/')

    return render(request, "form.html", {"form": form, "title": title, 'errors': form.non_field_errors()})

form.html

 <form method='POST' action='' enctype="multipart/form-data">{% csrf_token %}
        {{ form.non_field_errors }}
        <table align="center">
            <tr>
                <td>{{ form.username.label_tag }}</td>
                <td>{{ form.username }}</td>
            </tr>
            <tr>
                <td>{{ form.password.label_tag }}</td>
                <td>{{ form.password }}</td>
            </tr>
      </table>
        <div id="wrapper">
        <button id="button" type="submit">Login</button>
        </div>
    </form>

2 个答案:

答案 0 :(得分:2)

来自django.contrib.auth的{​​{3}}函数是这样写的,

  

该函数将凭据作为关键字参数,默认情况下的用户名和密码,针对每个身份验证后端进行检查,如果凭据对后端有效,则返回User对象。如果凭据对任何后端无效,或者后端引发PermissionDenied,则返回None

因此,如果您想要提高密码检查错误,那么应该在调用authenticate函数之前。您可能需要检查用户模型本身。您可以在表单或视图中进行验证。

您可以在登录前检查用户是否有效,

from django.contrib.auth.models import User

class UserLogInForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        #if username and password:
        # user = get_user_model()
        try:            
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise forms.ValidationError("This user does not exist!")  
        if user and not user.check_password(password):
            raise forms.ValidationError("Incorrect password!"):
        if user and not user.is_active:
            raise forms.ValidationError("This user is no longer active.")
        return super(UserLogInForm, self).clean(*args, **kwargs)

views.py

user = authenticate(username=username, password=password)
if user is not None:
    login(request, user)
    return redirect('/')
return render(request, "form.html", {"form": form, "title": title, 'errors': form.non_field_errors()})

答案 1 :(得分:0)

你可以修改你的form.html :)这里是示例代码:

注意:我认为你已经知道如何使用bootstrap。

 {% if user is not None %}
 <div class="alert alert-danger alert-dismissable">
       <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <p>The username does not exist!</p>
 </div>
{% endif %}

别忘了{%endif%}功能。

嗯,这只是Django的基本功能。

此外,您可以在views.py

中简化登录
def User_Logins(request):
if request.method == 'POST':
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')

    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        login(request, user)
        return redirect('/')
    return redirect('/')
return render(request, './', {'Login_form': UserLoginForm})