在内联字段Django中引发验证错误

时间:2018-11-29 08:52:54

标签: django django-models

我有一个包含 TabularInline 的模型,并且我想在条件无效时引发验证错误。 我的父母模型:

@admin.register(Even)
class EventAdmin(admin.ModelAdmin):
    list_display = ['id', 'title']
    list_display_links = ['id', 'title]
    inlines = [EventSpecialPriceInline]

还有我的TabularInline:

class EventSpecialPriceInline(admin.TabularInline):
    model = EventSpecialPrice
    extra = 0
    can_delete = True

我要引发的错误是当行的价格为负EventSpecialPrice.price < 0

2 个答案:

答案 0 :(得分:1)

您可以在模型字段中使用MinValueValidator

class EventSpecialPrice(models.Model)
    price = models.FloatField(validators=[MinValueValidator(0)])

答案 1 :(得分:0)

我添加了BaseInlineFormSet,并使用了form.clean

from django.core.exceptions import ValidationError
from django.forms.models import BaseInlineFormSet

class EventSpecialPriceInlineFormSet(BaseInlineFormSet):
    def clean(self):
        super(EventSpecialPriceInlineFormSet, self).clean()
        for form in self.forms:
            if form.cleaned_data and not form.cleaned_data.get('DELETE', False):
                if form.cleaned_data.get('price') < 0:
                    raise ValidationError('Price should be positive')

在我的TabularInline中,我定义了一个formset

class EventSpecialPriceInline(admin.TabularInline):
    model = EventSpecialPrice
    formset = EventSpecialPriceInlineFormSet
    extra = 0
    can_delete = True