问题
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