用户管理器方法create()和create_user() [英] User manager methods create() and create_user()
问题描述
我遇到一些 create()
方法的可疑行为用户
对象管理器。如果您使用此方法,则不需要密码
对于创建用户
对象而言。因此,您得到用户
与空白密码
。如果您使用 create_user
方法,并且不指定密码
,则会创建 User
使用不可用的密码(通过到 set_unusable_password()
)。
I have encountered with some suspicious behavior of create()
method of User
object manager. Looks like password
field isn't required for creating User
object if you use this method. In result you get User
with blank password
. In case when you use create_user
method and don't specify password
it creates User
with unusable password (through to set_unusable_password()
).
我不知道为什么 create()
方法不会引发异常
当您尝试创建没有密码
- 在文档中指定该字段是必需的。
create()
方法/文档中有问题
I am not sure why create()
method doesn't raise exception
when you try to create user without password
- in documentation it's specified that this field is required.
Is something wrong in create()
method/documentation?
推荐答案
这就是为什么用户模型有一个自定义管理器,其中包含 UserManager.create_user()
创建用户的方法。在用户
实例中使用 QuerySet.create()
方法有两个问题:
That's exactly why the user model has a custom manager with a UserManager.create_user()
method for creating users. There are two problems with using the QuerySet.create()
method on User
instances:
-
如果您运行管理命令
python manage.py sql
,请注意auth_user
schema:
If you run the management command
python manage.py sql
, pay attention to theauth_user
schema:
CREATE TABLE "auth_user" (
...
"password" varchar(128) NOT NULL,
...
)
在SQL中,空字符串''
不等于 NULL
,即 ISNULL('')!= TRUE
。
In SQL, an empty string, ''
, does not equate to NULL
, i.e. ISNULL('') != TRUE
.
QuerySet.create() / code>和
QuerySet.update()
不要触发模型验证。模型验证仅在 ModelForm
实例调用 Model.full_clean()
实例方法时发生。
QuerySet.create()
and QuerySet.update()
do not trigger model validation. Model validation only happens when ModelForm
instances call the Model.full_clean()
instance method.
在使用 QuerySet
API的上下文中提高验证错误,直接在Django中没有任何意义。这就是为什么你可以像 User.objects.create(username ='foo',password ='')
这样做,即使 CharField()。validate (value ='',None)
将为一个空白字符串引发 ValidationError
Raising a validation error in the context of working with the QuerySet
API directly simply makes no sense in Django. That's why you can do something like User.objects.create(username='foo', password='')
even though CharField().validate(value='', None)
would raise a ValidationError
for a blank string.
由于上述原因,您应该推迟使用 User.objects.create()
并依赖于提供的 User.objects.create_user()
方法从模型的自定义管理器。
For the reasons above, you should defer from using User.objects.create()
and rely on the supplied User.objects.create_user()
method from the model's custom manager.
这篇关于用户管理器方法create()和create_user()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!