用户ForeignKey与Django管理员的默认值 [英] Default value for user ForeignKey with Django admin

查看:188
本文介绍了用户ForeignKey与Django管理员的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

author = models.ForeignKey(User)

是有什么办法可以设置这个字段的默认值来自动选择登录的用户?我知道您可以在保存方式中执行此操作,但是我的客户端已经要求在编辑时自动默认登录用户,以避免混淆。

Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has requested that it automatically defaults to the logged in user at edit time to avoid confusion.

本文介绍如何在保存期间进行更新,而不是在编辑时间

This article goes into how to update it during save, just not at edit time.

推荐答案

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'author':
            kwargs['initial'] = request.user.id
        return super(MyModelAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs
        )

这篇关于用户ForeignKey与Django管理员的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆