1
votes

I create CustomUser class that extends AbstractUser, and add a ForeignKey field that reference to City Model

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']

I add the CustomUser to setting:

AUTH_USER_MODEL = "myapp.CustomUser"

When I tried to syncdb, it prompted me to create super user, when I fill in the city, I got this error:

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'

can someone explain to me why ? I'm still a newbie in django, thanks

1

1 Answers

0
votes

You can't set a required field to be a foreign key according to the docs. There's a ticket open with something similar to what you're encountering. I'd suggest subclassing CustomUserManager and override the create_superuser method on it, then use it for the objects manager on your CustomUser model.