有一个发票模型和两个定价模型来计算结算金额。我希望Django admin上的Invoice项目的详细信息页面显示由Invoice模型(pricing_type
)的属性确定的唯一一个内联。
为了实现上述目标,我编写了下面的代码,但是当我使用修改后的django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with']
在Django admin上保存Invoice项时,它引发了一个错误(pricing_type
)。如何在可切换的详细页面上进行内联?
class Invoice(models.Model):
pricing_type = models.CharField(
max_length=1,
choices=(
('A', 'Pricing type A'),
('B', 'Pricing type B'),
),
default='A')
class PricingA(models.Model):
invoice = models.ForeignKey(Invoice, models.CASCADE)
class PricingB(models.Model):
invoice = models.ForeignKey(Invoice, models.CASCADE)
class PricingAInline(admin.TabularInline):
model = PricingA
class PricingBInline(admin.TabularInline):
model = PricingB
@admin.register(Invoice)
class InvoiceAdmin(admin.ModelAdmin):
inlines = [PricingAInline, PricingBInline]
def get_formsets_with_inlines(self, request, obj=None):
for inline in self.get_inline_instances(request, obj):
if isinstance(inline, PricingAInline) and obj is not None and obj.pricing_type == 'A':
yield inline.get_formset(request, obj), inline
elif isinstance(inline, PricingBInline) and obj is not None and obj.pricing_type == 'B':
yield inline.get_formset(request, obj), inline
continue
答案 0 :(得分:0)
我决定添加自定义模板和自定义标记,以便在模板级别而不是get_formsets_with_inlines()
中过滤内联内容。它按我的意愿运作。
{% load i18n admin_urls static admin_modify %}
{% load customs %}
<div class="js-inline-admin-formset inline-group" id="{{ inline_admin_formset.formset.prefix }}-group"
data-inline-type="tabular"
data-inline-formset="{{ inline_admin_formset.inline_formset_data }}"
{% visible_inline adminform.form.instance.pricing_type.class_name inline_admin_formset.opts.model %}>
...
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def visible_inline(class_name, inline):
if class_name != inline.__class__.__name__:
return mark_safe('style="display:none"')