开发者

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 C开发者_JAVA技巧omments', 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)


It can be done.


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


To detect current logged in user

http://docs.djangoproject.com/en/dev/topics/auth/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜