Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out

ERRORS: blog.Post.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 know that I need to swap in settings.AUTH_USER_MODEL for auth.User, but for some reason doing this causes my blog to not show up. The routing is correct when I try to view blog from navigation bar but there is no content anymore. I also cannot login or create a new user on Django admin. These issues started occuring with setting an AUTH_USER_MODEL in settings for accounts.

blog/models.py

from django.db import models
from django.utils import timezone
from fitness_project import settings


class Post(models.Model):
    author = models.ForeignKey('auth.User', related_name='User')
    #author = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello',
    'blog',
    'membership',
    'accounts',
    'django_forms_bootstrap',
]

AUTH_USER_MODEL = 'accounts.User'

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'accounts.backends.EmailAuth',
)

blog/admin.py

from django.contrib import admin
from .models import Post

admin.site.register(Post)
like image 752
Merialc Avatar asked Jan 30 '23 11:01

Merialc


1 Answers

Since you have set AUTH_USER_MODEL = 'accounts.User', your model should be:

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL)

However, it is extremely difficult to switch to a custom user model for an existing project. If you are trying to do this, you may find it easiest to drop your database, delete your migrations, then re-run makemigrations and migrate.

like image 61
Alasdair Avatar answered Feb 08 '23 15:02

Alasdair