Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I import User model in django?

I am building a django web app with a custom user model which extends the AbstractBaseUser. In one of my models I need to use this custom user model:

from accounts.models import User

class History(models.Model):
    user = models.ForeignKey(User)
    job = models.ForeignKey(Job)

When I try to run the python manage.py makemigrations command this error message is outputted:

ImportError: cannot import name User

In my settings.py I do the following to let django know that there is a custom user model:

AUTH_USER_MODEL = "accounts.User"

I am puzzled as to what I am doing wrong. Surely there must be a way to import this model that I do not know of. How do I fix this?

I have tried to use the get_user_model() method, however it doesn't work in the model as the models haven't loaded yet. This is therefore not a solution. Any other ideas?

Thank you in advance.

like image 976
Tom Finet Avatar asked Aug 30 '25 16:08

Tom Finet


1 Answers

You can do as follows:

from django.conf import settings
class History(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    job = models.ForeignKey(Job)

Please refer to documentation for more details.

If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model.

get_user_model()[source]

Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active user model – the custom user model if one is specified, or User otherwise.

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. For example

like image 140
Gagik Sukiasyan Avatar answered Sep 02 '25 05:09

Gagik Sukiasyan