A longstanding inconvenience posting on my site has been selecting myself as the Author for each post. Now the logged-in user’s profile (me) is the default when creating a new post.
My original mistake was having a Profile model unconnected to the Django User model. Profiles contain extra data like a photo, short bio, and linked to profiles on other websites. These fields end up making the h-card
on the homepage and for each post.
I connected them using a one-to-one relationship
If you wish to store information related toUser
, you can use aOneToOneField
to a model containing the fields for additional information.
— Extending the User model, Django Docs
class Profile(models.Model):
# …
+ user = models.OneToOneField(User, on_delete=models.CASCADE)
My posts already had a foreign key to the Profile model as an author
property, and I am using a base Admin class to provide common Publishing functionality in the Admin.
To default the Author select to the logged in User’s now-connected Profile, I found this snippet. I added it to that base class so every Admin that inherits it automatically gets the new behavior.
class PublishableAdmin(PublishableMixin, admin.ModelAdmin):
+ def get_changeform_initial_data(self, request):
+ get_data = super(PublishableAdmin, self).get_changeform_initial_data(request)
+
+ if hasattr(request.user, "profile"):
+ get_data['author'] = request.user.profile.pk
+
+ return get_data
#…
So far it’s working great. It’s wonderful to no longer have to select myself as the author every time I post.