[英]In Django custom user manager, difference between create_user and _create_user()?
I'm trying to work through the tutorials for a Django custom user manager. 我正在尝试完成Django自定义用户管理器的教程。 Most of them override create_user() and create_super_user() like the documentation says to do, but this tutorial leaves those two methods alone and instead overrides _create_user() 正如文档中所说的那样,大多数方法都覆盖了create_user()和create_super_user(),但是本教程将这两个方法保留下来,而是覆盖了_create_user()
http://www.caktusgroup.com/blog/2013/08/07/migrating-custom-user-model-django/ http://www.caktusgroup.com/blog/2013/08/07/migrating-custom-user-model-django/
Is this correct? 这个对吗? What is the difference between overriding _create_user() vs create_user()? 覆盖_create_user()与create_user()有什么区别?
Here is both of the code of the _create_user, create_super_user and create_user method. 这是_create_user,create_super_user和create_user方法的两个代码。
def _create_user(self, username, email, password,
is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
user = self.model(username=username, email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email=None, password=None, **extra_fields):
return self._create_user(username, email, password, False, False,
**extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
return self._create_user(username, email, password, True, True,
**extra_fields)
As you can see that the create_user and create_super_user method is calling the _create_user function. 如您所见,create_user和create_super_user方法正在调用_create_user函数。 underscore at the beginning of a method means that the function is only for internal use. 方法开头的下划线表示该函数仅供内部使用。 It is fine to override the internal method, but, according to my opinion, it is better by design to override the public method. 覆盖内部方法很好,但是,根据我的观点,设计上最好覆盖公共方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.