django - 用户不会验证 Django
问题描述
我已经问过这个问题几次,并且一直在努力解决这个问题,但仍然无法正常工作。用户不会在 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})
这是我的forms.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
解决方案
我认为这是因为user.is_active = False
如果将其设置为True
,则仅允许任何用户进行身份验证并尝试登录 Django,请在文档is_active中检查这一点,如果您不希望这种默认行为,他们确实有另一个选项它说
如果要允许非活动用户登录,可以使用 AllowAllUsersModelBackend 或 AllowAllUsersRemoteUserBackend
推荐阅读
- python - 如何将二维列表写入文件
- python - 将数据存储到 SQL 不能使用我的 sql 连接器和 scrapy
- javascript - 如何防止 Electron 中的多个窗口实例?
- highcharts - 有没有办法让一列比其他列宽?
- postgresql - 使用 jdbc 模板从 Spring Boot 调用 postgres 存储过程
- python-3.x - 为什么 append() 不附加交换的列表。它正在附加原始字符串但打印交换列表
- javascript - 使用数组反应钩子 useState 导致缺少渲染调用
- javascript - 来自codeigniter中下拉选择的AJAX POST
- node.js - 抛出新的 mongoose.Error.MissingSchemaError(name); MissingSchemaError:尚未为模型“Comapign”注册架构
- django - 如何在 Django 表单中使用 BaseInlineFormSet?