django 无法验证AuthForm

jrcvhitl  于 2023-03-04  发布在  Go
关注(0)|答案(2)|浏览(104)

我正在开发我的应用的登录视图,为了做到这一点,我使用了Django内置的验证表单,但当我试图验证表单时,它返回False,我不知道为什么。

    • 型号. py**
class User(AbstractUser):
    '''
    Model that represents a user in the database
    '''
    first_name = models.CharField(max_length=50, null=False, blank=False)
    last_name = models.CharField(max_length=50, null=False, blank=False)
    username = models.CharField(max_length=50, null=False, blank=False, unique=True)
    email = models.EmailField(null=False, blank=False, unique=True)
    password1 = models.CharField(max_length=25)
    password2 = models.CharField(max_length=25)
    birthday = models.DateField(null=False, blank=False)
    verified = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'{self.first_name}: {self.email}'
    • 表单. py**
class AuthForm(AuthenticationForm):
    '''
    Form that uses built-in AuthenticationForm to handel user auth
    '''
    email = forms.EmailField(required=True,
        widget=forms.TextInput(attrs={
            'placeholder': 'Correo electrónico', 
            'name': 'email', 
            'type': 'email', 
            'class': 'form-control'
        }))
    password1 = forms.CharField(max_length=25, required=True,
        widget=forms.PasswordInput(attrs={
            'placeholder': 'Contraseña', 
            'name': 'password1', 
            'type': 'password', 
            'class': 'form-control'
        }))

    class Meta:
        model = User
        fields = ('email','password1', )
    • 登录. html**
<form action="{% url 'users:login' %}" method="post">
                                {% csrf_token %}
                                <div class="mb-3">{{ form.email }}</div>
                                <div class="mb-3">{{ form.password1 }}</div>
                                <div class="mb-3"><button class="btn btn-primary shadow d-block w-100" type="submit">Iniciar sesión</button></div>
                                <p class="text-muted">Recuperar contraseña</p>
                            </form>
    • 查看次数. py**
def login_page(request):

    if request.method == 'POST':

        form = AuthForm(request.POST)

        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password1')

            user = authenticate(request, username=email, password=password)
            
            if user is not None:
                login(request, user)
                return HttpResponseRedirect(reverse('network:profile'))
            else:
                return render(request, 'users/login.html', {'form': form})
        else:
            return render(request, 'users/login.html', {'form': form})

    return render(request, 'users/login.html', {
        'form': AuthForm(),
    })

错误发生在www.example.com_valid()中,即使我确信我在表单中引入了有效的数据,它也返回False。我的代码中是否有错误?如果有任何帮助,我将不胜感激。form.is_valid(), it returns False even when I'm sure that I'm introducing valid data to the form. Is there some error(s) in my code?, I would appreciate any help.

iezvtpos

iezvtpos1#

如果您尝试使用email进行身份验证,则需要考虑一些问题。
Django希望在AuthForm中看到一个username值,你可以通过覆盖默认的Auth用户模型来解决这个问题。
确保您已将电子邮件字段指定为User型号中的用户名,然后使用下面的链接按照指南进行操作。
请遵循以下指南:https://koenwoortman.com/python-django-email-as-username/
另外,使用password1password2会有问题,因为Django auth在验证用户对象时需要一个password字段。
我会删除password1password2,只使用默认的password字段,否则你必须重写Django在登录时引用password1password2的默认验证/密码方法。
然后,您的模型将如下所示:

class User(AbstractUser):
    '''
    Model that represents a user in the database
    '''
    
    USERNAME_FIELD = 'email' # add this

    first_name = models.CharField(max_length=50, null=False, blank=False)
    last_name = models.CharField(max_length=50, null=False, blank=False)
    username = models.CharField(max_length=50, null=False, blank=False, unique=True)
    email = models.EmailField(null=False, blank=False, unique=True)
    birthday = models.DateField(null=False, blank=False)
    verified = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'{self.first_name}: {self. Email}'

您还必须替换您的身份验证表单、模板和视图。以使用更新的"电子邮件"和"密码"字段
如有必要,请确保将更改迁移到用户模型。

ogsagwnx

ogsagwnx2#

我认为您大多数情况下使用form = AuthForm(request)而不是form = AuthForm(request.POST),因为request.POST返回表单方法,而不是要验证的数据

相关问题