管理站点自动获取当前用户

发布于 2024-09-16 01:58:10 字数 932 浏览 4 评论 0原文

我正在制作一个博客应用程序,并希望在通过管理站点提交新帖子时自动添加当前用户。有什么方法可以检测当前登录的用户并将其添加到帖子中吗?

这些是模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱要勇敢去追 2024-09-23 01:58:10
def save_model(self, request, obj, form, change):

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

我尝试了一下,效果很好。
这就是来源

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文