Reputation: 83
I am trying to create a blog app with models.py I want to set auth_user model primary key as foreign key to my model in blog app.After adding the appropriate code i am getting the following error?
from django.db import models
from django.conf import settings
# Create your models here.
class Post(models.Model):
title=models.CharField(max_length=100)
desc=models.TextField()
date=models.DateTimeField(auto_now=True)
author=models.ForeignKey("settings.AUTH_USER_MODEL",
on_delete=models.CASCADE)
ERRORS: blog.Post.author: (fields.E300) Field defines a relation with model 'User', which is either not installed, or is abstract. blog.Post.author: (fields.E307) The field blog.Post.author was declared with a lazy reference to 'blog.user', but app 'blog' doesn't provide model 'user'.
Upvotes: 2
Views: 532
Reputation: 477055
You should not use a string literal here, the settings.AUTH_USER_MODEL
[Django-doc] itself is a string that contains the name of the user model, as specified in the documentation:
AUTH_USER_MODEL
Default:
'auth.User'
The model to use to represent a User. (..)
You thus implement this like:
from django.db import models
from django.conf import settings
class Post(models.Model):
title=models.CharField(max_length=100)
desc=models.TextField()
date=models.DateTimeField(auto_now=True)
author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
The idea is that you either pass a reference to the class itself, or you use the a qualified name as a string for it. But 'settings.AUTH_USER_MODEL'
is not the qualified name of the user model.
Alternatively, you can use get_user_model(..)
[Django-doc]:
from django.db import models
from django.contrib.auth import get_user_model
class Post(models.Model):
title=models.CharField(max_length=100)
desc=models.TextField()
date=models.DateTimeField(auto_now=True)
author=models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
Upvotes: 2