How do I set a default user for blog posts in Django?

Viewed 81

My Blog model has a User field like following:

from django.contrib.auth.models import User

class Blog:
    author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog', default=User('monty'))

This works as in I can see 'monty' set as a default user in the admin interface when I create a blog post. However, when I make migrations, I get the following error:

ValueError: Cannot serialize: <User: >
There are some values Django cannot serialize into migration files.

I also tried this:

default=User.objects.filter(username='monty'))

and that returns a slightly different error when I make migrations:

ValueError: Cannot serialize: <User: monty>
There are some values Django cannot serialize into migration files.

Does anyone know how to get past this error?

1 Answers

You can make a callable that determines the User object, so:

from django.conf import settings
from django.contrib.auth import get_user_model

def get_monty():
    if get_monty.user:
        return user
    user, __ = get_user_model().get_or_create(username='monty')
    get_monty.user = user
    return user
    
get_monty.user = None

class Blog(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='blog',
        default=get_monty
    )

That being said, I think it makes no sense to specify a default here. Your views can determine the logged in user and set that as the author. By using a default you likely will eventually end up with some Posts for which the view did not implement the logic, and are thus all assigned to monty, it thus will silence an error that probably should not be silenced.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Related