Ulfric Storm
Ulfric Storm

Reputation: 129

Modify admin.py so that it's only offering the current logged-in user for the models.ForeignKey(User)

I have a blog where more users should log in via admin-panel and publish some content. My problem is that i only want to allow the user to publish under his username.

My models.py:

class Post(models.Model):
    author = models.ForeignKey(User)
    ...

How should the admin.py or models.py be modified?

Upvotes: 0

Views: 55

Answers (1)

hellsgate
hellsgate

Reputation: 6005

First, exclude the author field from the admin form. Then add the logged in user as author in the admin save_model method:

class PostAdmin(admin.ModelAdmin):
    exclude = ['author',]

    def save_model(self, request, obj, form, change):
        if obj.author is None:
            obj.author = request.user
        obj.save()

Upvotes: 2

Related Questions