Raise validation error in inline field Django

不羁的心 提交于 2021-02-18 18:54:38

问题


I have a model that contains a TabularInline, and I want to raise a validation error when a condition is not valid. My parent model:

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

And my TabularInline:

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

The error I want to raise is when a price of a row is negative EventSpecialPrice.price < 0


回答1:


You could use MinValueValidator for your model field

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



回答2:


I've added a BaseInlineFormSet and used 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')

And in my TabularInline I've defined a formset:

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


来源:https://stackoverflow.com/questions/53535051/raise-validation-error-in-inline-field-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!