Skip to main content
 首页 » 编程设计

python之Django ValidationError 只显示一个错误

2024年10月01日21JeffreyZhao

我正在尝试制作一个 Django 登录屏幕,例如当用户没有输入正确的密码时显示错误。 但我收到的唯一错误是“该用户不存在!”我怎样才能让其他错误信息显示出来?我的代码有什么问题?

表单.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) 

View .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()}) 

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

请您参考如下方法:

authenticate django.contrib.auth 中的函数是这样写的,

The function takes credentials as keyword arguments, username and password for the default case, checks them against each authentication backend, and returns a User object if the credentials are valid for a backend. If the credentials aren’t valid for any backend or if a backend raises PermissionDenied, it returns None.

所以,如果你想引发密码检查错误,应该在调用 authenticate 函数之前。您可能需要检查用户模型本身。您可以在表单或 View 中进行验证。

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

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