gpt4 book ai didi

django - 在表单中访问管理模型实例

转载 作者:行者123 更新时间:2023-12-04 06:19:28 26 4
gpt4 key购买 nike

class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm()

class ProductAdminForm(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
super(ProductAdminForm, self).__init__(*args, **kwargs)
self.fields['field1'] = forms.CharField(required=False)
self.fields['field2'] = forms.IntegerField()

如何将产品实例从 ProductAdmin 传递到 ProductAdminForm?我想根据产品实例提供不同的字段。

最佳答案

这个:

class ProductAdminForm(forms.ModelForm):
class Meta:
model = Product

def __init__(self, *args, **kwargs):
super(ProductAdminForm, self).__init__(*args, **kwargs)

product_instance = self.instance
if product_instance.id and product_instance.myField == "thatValue":
self.fields['field1'] = forms.CharField(required=False)
self.fields['field2'] = forms.IntegerField()

关于django - 在表单中访问管理模型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6777371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com