本文介绍了如何从 Django 中的 inlineadmin 获取当前模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我正在使用 formfield_for_manytomany.formfield_for_foreignkey" rel="noreferrer">django 文档.但在该函数中,我需要获取当前正在编辑的父对象.
I am using the formfield_for_manytomany
given in django documentation.
But inside that function I need to get the current parent object being edited.
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Cars.objects.filter(owner=person)
return super(myModel, self).formfield_for_manytomany(db_field, request, **kwargs)
如何获取正在编辑的人?
How can I get the person being edited?
推荐答案
如果 person
无法从 request
轻松获取,则可能需要通过覆盖手动传递ModelAdmin.get_form()
或 InlineModelAdmin.get_formset()
:
If the person
cannot be easily got from request
, you may need to manually pass it by overriding ModelAdmin.get_form()
or InlineModelAdmin.get_formset()
:
from functools import partial
class MyModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request, obj=obj)
return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
def formfield_for_dbfield(self, db_field, **kwargs):
person = kwargs.pop('obj', None)
formfield = super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == "car" and person:
formfield.queryset = Cars.objects.filter(owner=person)
return formfield
# or its inline
class MyInlineModelAdmin(admin.StackedInline):
def get_formset(self, request, obj=None, **kwargs):
kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request, obj=obj)
return super(MyInlineModelAdmin, self).get_formset(request, obj, **kwargs)
def formfield_for_dbfield(self, db_field, **kwargs):
person = kwargs.pop('obj', None)
formfield = super(MyInlineModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == "car" and person:
formfield.queryset = Cars.objects.filter(owner=person)
return formfield
或者
class MyModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request, obj=obj)
return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name != "car":
kwargs.pop('obj', None)
return super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
person = kwargs.pop('obj', None)
if db_field.name == "car" and person:
kwargs['queryset'] = Cars.objects.filter(owner=person)
return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
这篇关于如何从 Django 中的 inlineadmin 获取当前模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!