Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Admin site automatically get current user

I am making a blog application and want to automatically add the current user when I submit a new post through the admin site. Is there any way that I could detect the current logged-in user and add it to the post?

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 the 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)
like image 781
crodjer Avatar asked Nov 25 '25 18:11

crodjer


2 Answers

It can be done.

like image 118
Ignacio Vazquez-Abrams Avatar answered Nov 28 '25 08:11

Ignacio Vazquez-Abrams


def save_model(self, request, obj, form, change):

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

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

like image 34
ahmed Avatar answered Nov 28 '25 06:11

ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!