我下面舉個例子,我不知道如何在管理界面中設置一個驗證錯誤的每一行:添加驗證在Django管理主從接口(用於詳細記錄)
參考#添加驗證錯誤,該行forms.py
models.py:
from django.db import models
from django.core.exceptions import ValidationError
class Foo(models.Model):
name = models.CharField("Name", blank=True, max_length=300)
class Bar(models.Model):
name = models.CharField("Name", blank=True, max_length=300)
foo = models.ForeignKey('Foo', verbose_name='Foo')
admin.py
from django.contrib import admin
from .models import *
from .forms import *
class BarInline(admin.TabularInline):
model = Bar
formset = BarInlineFormset
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
model = Foo
inlines = [BarInline,]
forms.py
from django.db import models
from django import forms
from django.core.exceptions import ValidationError
class BarInlineFormset(forms.models.BaseInlineFormSet):
def clean(self):
data = self.cleaned_data
valid = True
for item in data:
if not item:
break;
if not item['name'].startswith('Bar'):
valid = False
# add validation error for that row
if not valid:
raise ValidationError('Form is not valid.')
return data
附:我使用Django的1.8.x的和Python 3.4
我想知道這與我所建議的有何不同。 – Wtower