【发布时间】:2019-02-13 16:56:14
【问题描述】:
我在 django 中做一个 Web 应用程序,用户可以在其中创建帐户。我以明文形式存储用户的密码,因为我的系统中的身份验证并不完全取决于密码,还取决于 otp。在注册的 POST 请求中,我突然面临的问题(之前工作正常)是“NOT NULL 约束失败:accounts_myuser.password”。我尝试删除数据库和迁移并重新迁移,但没有帮助。我在下面给出了 ModelForm 和 Model(custom one)。我的模型中只有两个字段,即“电子邮件”和“用户名”。它运行良好,我可以使用下面的代码更早地成功注册用户。谁能帮帮我?
forms.py
class UserCreationForm(forms.ModelForm):
password1 = forms.IntegerField(label='Password', min_value=0000, max_value=9999, widget=forms.PasswordInput)
password2 = forms.IntegerField(label='Password Confirmation', min_value=0000, max_value=9999,
widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email']
def clean_password1(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!")
if len(str(password1)) != 4 or len(str(password2)) != 4:
raise forms.ValidationError("Passwords should be of length Four!")
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.password = self.cleaned_data['password1']
if commit:
user.save()
return user
models.py
class MyUserManager(BaseUserManager):
def create_user(self, username, email, password=None):
if not email:
raise ValueError('Users must have an email')
user = self.model(
username = username,
email = self.normalize_email(email),
password = password
)
# user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password=None):
user = self.create_user(
username, email, password
)
user.is_admin = True
user.is_staff = True
user.set_password(password)
user.save(using=self._db)
return user
【问题讨论】:
-
你为什么展示你的经理而不是你的模特?您使用的是
create_user还是create_superuser?因为,如果您将空密码传递给这两种方法中的任何一种,都会触发此错误。 -
@RodrigoRodrigues 是的,这就是问题所在!没有生成并作为密码传递!给您带来的不便真的很抱歉!
-
好的,我一会儿写一个正确的答案
-
@RodrigoRodrigues 非常感谢!但是当我意识到我哪里出错时我就解决了!
-
当然可以,但是在 StackOverflow 中,我们总是尝试正确回答问题,因此当有相同问题的人在互联网上搜索时,他们可以轻松找到解决方案!
标签: django django-forms modelform notnull