3
votes

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)
2

2 Answers

8
votes

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.

0
votes

The answer by Alasdair is correct, but here's my little more modification to it.

As you have already imported - from fitness_project import settings , You can also assign a var named User, so you can use it next time in your model's fields

User = settings.AUTH_USER_MODEL

And then, as usual you can use User like this -

author = models.ForeignKey(User, related_name='User')