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 获取对象


基础教程推荐
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01