我自定义了默认的django用户模型,以使电子邮件为必需,用户名为可选。我有一个供用户输入信息并创建帐户的表格。他们输入电子邮件,名字,姓氏,密码,确认密码,然后选中条款/条件框。所有这些字段都是必填字段。
在我看来,我验证并清除了数据并将用户保存到数据库中。这是通过管理工具使用SQLite数据库和默认项目布局的。然后,我决定使用两个django推荐的项目布局。除了让我提交用户注册表格时,我使网站再次正常工作,它使用电子邮件和密码将用户保存在数据库中,但不保存名字或姓氏。
我确认名字和姓氏已传递到视图。这是有道理的,因为它以前可以工作。在项目布局更改后,也许某个地方需要更新设置?我真的不确定发生了什么,因为它会将用户信息保存到数据库中,而不是将所有用户信息保存到数据库中。
任何帮助将不胜感激!这是我第一个真正的django项目,现在我很困惑。
来自views.py:
def signup(request):
"""
signup page: form to collect user info if they want to sign up
"""
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
email = form.cleaned_data.get('email')
username = form.cleaned_data.get('username')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
password = form.cleaned_data.get('password')
new_user = User.objects.create_user(email=email,
username=username,
first_name=first_name,
last_name=last_name,
password=password)
new_user.save()
login(request=request, user=new_user)
#redirect
return redirect('construction')
else:
# Append css error class to each field that has errors
for field in form.errors:
if field == '__all__':
continue
form[field].field.widget.attrs['class'] += ' field-error'
else:
form = UserForm()
return render(
request,
'signup.html',
context={'form': form}
)
来自models.py:
class User(AbstractUser):
username_validator = UnicodeUsernameValidator()
username = models.CharField(_('username'),
max_length=50,
unique=False,
help_text=_('Optional. 50 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
blank=True,
null=True)
email=models.EmailField(_('email address'), unique=True, blank=False, error_messages={
'unique': _("A user with that email address already exists")
})
first_name = models.CharField(_('first name'), max_length=30, blank=False)
last_name = models.CharField(_('last name'), max_length=50, blank=False)
USERNAME_FIELD = 'email'
# REQUIRED_FIELDS should not include the USERNAME_FIELD or password since these will always be prompted for,
# per the documentation: https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = UserManager()
来自forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput(attrs={"class": "form-control",
"placeholder": "Password",
"required": "required"}))
confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={"class": "form-control",
"placeholder": "Confirm",
"required": "required"}))
terms_conditions = forms.BooleanField(required=True,
initial=False,
widget=forms.CheckboxInput(attrs={"class": "form-check-input",
"type": "checkbox",
"id": "invalidCheck",
"required": "required"}))
class Meta:
model = User
fields = ("first_name", "last_name", "email")
widgets = {
"first_name": forms.TextInput(attrs={"class": "form-control",
"placeholder": "First",
"required": "required"}),
"last_name": forms.TextInput(attrs={"class": "form-control",
"placeholder": "Last",
"required": "required"}),
"email": forms.EmailInput(attrs={"class": "form-control",
"placeholder": "Email",
"required": "required"}),
}
def clean(self):
cleaned_data = super(UserForm, self).clean()
#check that passwords are the same
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
raise forms.ValidationError("password and confirmation password do not match")
terms_agreement = cleaned_data.get("terms_conditions")
print("Terms + conditions value: " + str(terms_agreement))
答案 0 :(得分:0)
自己弄清楚。如果有其他问题,我将发布问题。
在我的models.py中:我将_create_user调用更改为“ first_name”和“ last_name”,但忘记了将这些字段添加到user = self.model(username=username, email=email, **extra_fields)
语句中
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, first_name, last_name, username, password, **extra_fields):
"""
Create and save a user with the given email, first name, last name, username, and password.
"""
if not email:
raise ValueError('Email is required')
if not first_name:
raise ValueError('First name is required')
if not last_name:
raise ValueError('Last name is required')
if not password:
raise ValueError('Password is required')
email = self.normalize_email(email)
username = self.model.normalize_username(username)
user = self.model(username=username, email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_user(self, email, first_name, last_name, username=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, first_name, last_name, username, password, **extra_fields)
def create_superuser(self, email, first_name, last_name, username=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, first_name, last_name, username, password, **extra_fields)