我试图切换到自定义用户身份验证,以便可以在需要时更轻松地对用户模型进行更改。我在https://docs.djangoproject.com/en/2.1/topics/auth/customizing/处查看文档,但是我的表单出现问题。
models.py
from django.contrib.auth.models import AbstractBaseUser
class DefaultUser(AbstractBaseUser):
pass
Forms.py包含以下
from .models import DefaultUser
from django.core.validators import EmailValidator
from django.utils.crypto import get_random_string
from django.contrib.auth import password_validation
from django import forms
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.forms import UsernameField
class UserCreateForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
'Invalid_Email_Address': _("Invalid Email Address"),
}
password1 = forms.CharField(
label=_("Password"),
strip=False,
widget=forms.PasswordInput,
help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
label=_("Password confirmation"),
widget=forms.PasswordInput,
strip=False,
help_text=_("Enter the same password as before, for verification."),
)
class Meta:
model = DefaultUser
fields = [
"username",
"first_name",
"last_name",
]
field_classes = {'username': UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self._meta.model.USERNAME_FIELD in self.fields:
self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True})
self.fields[self._meta.model.USERNAME_FIELD].label = 'Email'
def clean_username(self):
username = self.cleaned_data.get('username')
validate_username_is_email = EmailValidator()
print(username)
print(validate_username_is_email(username))
if validate_username_is_email(username):
raise forms.ValidationError(
self.error_messages['Invalid_Email_Address'],
code='Invalid_Email_Address',
)
return username
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def _post_clean(self):
super()._post_clean()
# Validate the password after self.instance is updated with form data
# by super().
password = self.cleaned_data.get('password2')
if password:
try:
password_validation.validate_password(password, self.instance)
except forms.ValidationError as error:
self.add_error('password2', error)
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data.get('username')
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
我尝试运行迁移时遇到的错误是 django.core.exceptions.FieldError:为DefaultUser指定了未知字段(名字,姓氏,用户名),这似乎是由表单中的Meta类引起的,因为如果我删除了一个字段,错误更改。虽然当Meta指向模型= User时一切正常。
我也确实将它添加到了我的设置页面
AUTH_USER_MODEL = "accounts.DefaultUser"
而admin.py有
from django.contrib import admin
from .models import DefaultUser
admin.site.register(DefaultUser)
非常感谢您的帮助。
答案 0 :(得分:0)
AbstractBaseUser类不包含任何模型字段(密码和上次登录字段除外),因此即使在理论上也无法使用。您应该在DefaultUser模型类中定义模型字段以供使用,请选中example。
由于您尚未注册Admin类,因此该管理部分也无法正常工作。
如果您更仔细地阅读本文档,则应该最终获取它。
AbstractBaseUser类,您也可以在BaseUser的源代码中查看一些提示