2016-08-07 69 views
1

我跟着這個定製的Django用戶模型的代碼example幾乎一字不差,當我嘗試創建它的self.model與錯誤的Django的UserManager create_user與「NoneType」對象故障不可調用的

最後一個參數失敗用戶
TypeError: 'NoneType' object is not callable 

相關的代碼片斷如下:

class MyUserManager(BaseUserManager): 

def create_user(self, email, password=None, 
       first_name=None, 
       last_name=None 
       ): 
    now = timezone.now() 
    if not email: 
     raise ValueError('The given email must be set') 
    email = self.normalize_email(email) 

    user = self.model(email=email, 
         first_name=first_name, 
         last_name=last_name 
        ) 

    user.set_password(password) 
    user.save(using=self._db) 
    return user 

class MyUser(AbstractBaseUser, PermissionsMixin): 

email = models.EmailField(_('email address'), max_length=254, unique=True) 
first_name = models.CharField(_('first name'), max_length=30, blank=False) 
last_name = models.CharField(_('last name'), max_length=30, blank=False) 

objects = MyUserManager() 

USERNAME_FIELD = 'email' 
REQUIRED_FIELDS = [] 

class Meta: 
    verbose_name = _('user') 
    verbose_name_plural = _('users') 

def get_full_name(self): 
    """ 
    Returns the first_name plus the last_name, with a space in between. 
    """ 
    full_name = '%s %s' % (self.first_name, self.last_name) 
    return full_name.strip() 

看起來self.modelNone,但我認爲有在MyUserobjects = MyUserManager()是世界衛生大會兩者聯繫在一起。

回溯:

Traceback (most recent call last): 
    File "api/tests/test_location.py", line 24, in setUp 
    first_name=first_name, last_name=last_name) 
    File "api/models.py", line 99, in create_user 
    last_name=last_name 
TypeError: 'NoneType' object is not callable 

我叫它像這樣:

MyUserManager().create_user(email=email, password=password, first_name=first_name, 
      last_name=last_name) 
+0

請顯示* full * traceback。 –

+0

添加了完整的追溯 – cph2117

回答

3

將有附着的MyUserManager該實例,如果你直接實例並調用create_user方法一樣,沒有模型實例所以。您應該撥打您的MyUser型號:

my_user = MyUser.objects.create_user(email=email, 
            password=password, 
            first_name=first_name, 
            last_name=last_name) 
+0

但是,你怎麼能通過UserManager創建一個用戶?或者那不是django慣例?如果不是那麼UserManager是什麼? – cph2117

+0

@ cph2117'MyUser.objects'是管理器的一個實例(請參閱'objects = MyUserManager()') –

+0

Ohhh好的我誤解了範例。謝謝 – cph2117

相關問題