我正在创建一个博客应用程序,并希望在我通过管理站点提交新帖子时自动添加当前用户。有什么方法可以检测当前登录用户并将其添加到帖子中吗?
这些是模型:
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)
在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)
答案 0 :(得分:3)
答案 1 :(得分:2)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
我试过了,效果很好。 这是来源
答案 2 :(得分:0)