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 获取对象
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何将一个类的函数分成多个文件? 2022-01-01
