用户将不对Django进行身份验证

时间:2019-09-05 16:56:37

标签: django django-authentication django-users

我已经问过几次这个问题,并且已经为此工作了几天,但仍然无法正常工作。用户将无法在Django中进行身份验证。我正在使用基本用户模型。我的用户未获得身份验证,表单也未提交,我不清楚发生了什么问题。

这是我的views.py:

 def payments(request):
    if request.method == "POST":
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False # this is because they need to fill out another form before I deem them active
            user.set_password(form.cleaned_data['password1'])
            user.save() 
            user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
            if user.is_authenticated:
                login(request, user, backend='django.contrib.auth.backends.ModelBackend')
                return redirect('agreements')
            else: 
                raise ValidationError("User could not be authenticated.")            
        else:
            raise ValidationError("Form is not valid. Try Again.")
    else:
        form = CustomUserCreationForm()
  return render(request, 'register.html', {'form': form})

这是我的表格。py:

class CustomUserCreationForm(forms.ModelForm):
    username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"}))
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': "form-control"}))
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': "form-control"}))
    first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': "form-control"}))
    last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': "form-control"}))
    email = forms.CharField(label= 'Email', widget=forms.EmailInput(attrs={'class': "form-control"}))

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'username']

    def clean_password(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords do not match")
        return password2


    def save(self, commit=True):
        user = super(CustomUserCreationForm, self).save(commit=False)
        user.username = self.cleaned_data['username']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']
        user.set_password(self.cleaned_data['password1'])

        if commit:
            user.save()
        return user

1 个答案:

答案 0 :(得分:0)

我认为这是因为如果将此user.is_active = False设置为True,则只有任何通过身份验证并尝试登录Django的用户才被允许,请在文档{{3}中进行检查},如果您不希望这种默认行为

  

如果要允许不活动的用户登录,则可以使用AllowAllUsersModelBackend或AllowAllUsersRemoteUserBackend