添加自定义用户模型后无法创建超级用户

时间:2014-05-04 15:19:38

标签: python django

我创建了扩展AbstractUser的CustomUser类,并添加了一个引用City Model的ForeignKey字段

class City(models.Model):
    created_dt = models.DateTimeField("Created Time", auto_now_add=True)
    code = models.CharField(max_length=64, unique=True)
    name = models.CharField(max_length=64)

class CustomUser(AbstractUser):
    city = models.ForeignKey(City)
    REQUIRED_FIELDS = ['city']

我将CustomUser添加到设置:

AUTH_USER_MODEL = "myapp.CustomUser"

当我尝试syncdb时,它提示我创建超级用户,当我填写城市时,我收到此错误:

City: 1
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 116, in handle
    user_data[field_name] = field.clean(raw_value, None)
  File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 255, in clean
    self.validate(value, model_instance)
  File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1201, in validate
    using = router.db_for_read(model_instance.__class__, instance=model_instance)
  File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/utils.py", line 250, in _route_db
    return hints['instance']._state.db or DEFAULT_DB_ALIAS
AttributeError: 'NoneType' object has no attribute '_state'
有人可以向我解释原因吗? 我还是django的新手,谢谢

1 个答案:

答案 0 :(得分:0)

您无法根据docs将必填字段设置为外键。 ticket打开的内容类似于您遇到的内容。我建议对CustomUserManager进行子类化并覆盖create_superuser方法,然后将其用于CustomUser模型上的对象管理器。