管理站点自动获取当前用户
我正在制作一个博客应用程序,并希望在通过管理站点提交新帖子时自动添加当前用户。有什么方法可以检测当前登录的用户并将其添加到帖子中吗?
这些是模型:
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以做到。
It can be done.
我尝试了一下,效果很好。
这就是来源
I tried it and it worked well .
and this is the source
检测当前登录的用户
http://docs.djangoproject.com/en/dev /主题/授权/
To detect current logged in user
http://docs.djangoproject.com/en/dev/topics/auth/