Using Your Django Custom User Model as Foreign Key

The Django docs recommend that when you create a new project you use a custom user model. Doing so lets you do things like add fields to store information about your users quite easily.

There are at least 4 ways to extend the user model on a new project. Each has its own advantages. On an existing project you might try this approach to extend the user model.

If you are using django-cookiecutter like me, you'll get a custom user model automatically. In that case you'll get a custom user model based on the AbstractUser class. You'll find it in {your_app}.users.models and it will look something like this:

class User(AbstractUser):
    class Meta:
        unique_together = (("name", "agency"),)
    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(_('Name of User'), blank=True, max_length=255)
    is_active = models.BooleanField(_('active'), default=True,
                                    help_text=_('Designates whether this user should be treated as '
                                                'active. Unselect this instead of deleting accounts.'))

Adding a new field is as easy as defining it in the class and running the migrations. Simple. But what if you want create a foreign key relationship between the User model and another model you define?

When I tried to do something like this:

class SomeRelatedModel(models.Model):
    user = models.ForeignKey('User' on_delete=models.CASCADE, )

I received this error when I ran my migrations: Field defines a relation with model 'User', which is either not installed, or is abstract.

When I try to import the model first and then use it I get this error: ImportError: cannot import name 'User'. No matter how I did my imports I couldn't get it working correctly.

So what is the solution? It is in the docs of course where they tell us "When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting." In my example that would look like this:

from django.conf import settings

class SomeRelatedModel(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,)

Comments

Comments powered by Disqus