0

I have created a custom user model which is working fine. The problem is when access the user from foreign key, it throws me :

DETAIL: Key (author_id)=(51) is not present in table "auth_user".

My custom user is userauth, clearly the model still looking for the original User model instead of the custom one.

Here is what I did:

#settings.py
AUTH_USER_MODEL = 'userauth.UserAuth'

#models.py
from django.conf import settings
User = settings.AUTH_USER_MODEL

class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    author = models.ForeignKey(User, null=True,blank=True,default=None)

#admin.py
class AdminPost(admin.ModelAdmin):
   def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()
dev-jim
  • 2,404
  • 6
  • 35
  • 61

1 Answers1

0

I would do something like this instead (don't bother assigning variables):

models.py:

from django.conf import settings

class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    # You don't need 'default=None'
    author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
jape
  • 2,861
  • 2
  • 26
  • 58
  • Yes, you are right. The 'default=None' caused the problem. Wonder why it will affect the custom user model though. – dev-jim Aug 06 '15 at 05:03
  • @dev-jim When you set `default=None`, you are overriding the ForeignKey and saying, "Make the field equal to nothing." Then trying to call that field, you are trying to call nothing. In essence, you're having a conversation with no body when you try to call it from the database. – jape Aug 06 '15 at 14:51
  • Thanks for the explanation! – dev-jim Aug 06 '15 at 16:59