django admin inlines: get object from formfield_for_foreignkey(django admin inlines:从 formfield_for_foreignkey 获取对象)
问题描述
我正在尝试在 django 管理员内联中过滤外键字段中显示的选项.因此,我想访问正在编辑的父对象.我一直在研究,但找不到任何解决方案.
I am trying to filter the options shown in a foreignkey field, within a django admin inline. Thus, I want to access the parent object being edited. I have been researching but couldn't find any solution.
class ProjectGroupMembershipInline(admin.StackedInline):
model = ProjectGroupMembership
extra = 1
formset = ProjectGroupMembershipInlineFormSet
form = ProjectGroupMembershipInlineForm
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == 'group':
kwargs['queryset'] = Group.objects.filter(some_filtering_here=object_being_edited)
return super(ProjectGroupMembershipInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
我在编辑对象时验证了 kwargs 是空的,所以我无法从那里获取对象.
I have verified that kwargs is empty when editing an object, so I can't get the object from there.
有什么帮助吗?谢谢
推荐答案
为了过滤可用于管理内联中的外键字段的选项,我重写了表单,以便可以更新表单字段的 queryset代码>属性.这样您就可以访问表单中正在编辑的对象 self.instance.所以是这样的:
To filter the choices available for a foreign key field in an admin inline, I override the form so that I can update the form field's queryset attribute. That way you have access to self.instance which is the object being edited in the form. So something like this:
class ProjectGroupMembershipInlineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProjectGroupMembershipInlineForm, self).__init__(*args, **kwargs)
self.fields['group'].queryset = Group.objects.filter(some_filtering_here=self.instance)
如果您执行上述操作,则不需要使用 formfield_for_foreignkey,它应该可以完成您描述的操作.
You don't need to use formfield_for_foreignkey if you do the above and it should accomplish what you described.
这篇关于django admin inlines:从 formfield_for_foreignkey 获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:django admin inlines:从 formfield_for_foreignkey 获取对象
基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
