Admin site automatically gets current user

I am making a blog application and want to automatically add the current user when I send a new message through the admin site. Is there a way so that I can detect the current registered user and add it to the message?

These are the models:

class Post(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField('Title', max_length=100)
    content = models.TextField('Content')
    comments_allowed = models.BooleanField('Allow Comments', default=True)
    time = models.DateTimeField('Time', auto_now_add = True)

And in admin.py:

class PostAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['title']}),
        (None,               {'fields': ['user']}),
        (None,               {'fields': ['content']}),
        (None,               {'fields': ['comments_allowed']}),
    ]
    list_display = ('title','user', 'time','comments_allowed','id',)
    list_filter = ['time']
    search_fields = ['title']
    date_hierarchy = 'time'    
admin.site.register(Post,PostAdmin)
+3
source share
3 answers
def save_model(self, request, obj, form, change):

    obj.user = request.user
    obj.save()

I tried and it worked well. and this is the source

+2
source

Source: https://habr.com/ru/post/1760895/


All Articles