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

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

问题描述

author = models.ForeignKey(User)

有什么方法可以设置这个字段的默认值来自动选择登录用户?我知道您可以在 save 方法中执行此操作,但我的客户要求它在编辑时自动默认为登录用户以避免混淆.

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
        )

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

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