HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'

Question:

Hello I had to rewrite my user model for add some filed, I used AbstractUser

My models:
It’s on blog app:

class Article(models.Model):
    author = models.ForeignKey(User , null=True, on_delete=models.SET_NULL , related_name='articles' , verbose_name='نویسنده')...

it’s on account app:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    is_authour = models.BooleanField(default=False, verbose_name="وضعیت نویسندگی")
    special_user = models.DateTimeField(default=timezone.now, verbose_name="کاربر ویژه تا")    

    def is_special_user(self):
        if self.special_user > timezone.now():
            return True
        else:
            return False 
    
    is_special_user.boolean = True
    is_special_user.short_description = "وضغیت کاربر ویژه"

I imported my User view in this way:

from account.models import User

And I added this to my setting:

AUTH_USER_MODEL = 'account.User'

when I migrate I get this error:

blog.Article.author: (fields.E301) Field defines a relation with the
model ‘auth.User’, which has been swapped out.
HINT: Update the relation to point at ‘settings.AUTH_USER_MODEL’.

I searched my error but I can’t find my solution

Asked By: Mahyar Mohamadpour

||

Answers:

I think you are importing User model from django auth app.

Change the author field in the Article model as follows:

class Article(models.Model):
    author = models.ForeignKey('account.User', null=True, on_delete=models.SET_NULL, related_name='articles', verbose_name='نویسنده')
    ...
Answered By: AminAli

The current User passed to the ForeignKey points to the auth.User right now, not your custom User.

As the HINT itself suggests, use settings.AUTH_USER_MODEL instead of User in your author field in Article model.

class Article(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name='articles', verbose_name='نویسنده')...
Answered By: S.B

Link to django docs: Using a custom user model

Did you register the model in the app’s admin.py?

Furthermore, changing the user model mid-project…this can be a hassle, look here: Changing to a custom user model mid-project

Answered By: Sophie Machen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.