2015-11-08 64 views
0

我下面舉個例子,我不知道如何在管理界面中設置一個驗證錯誤的每一行:添加驗證在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

回答

0

我有這個簡單的解決方案,工作完美:

admin.py

class BarInline(admin.TabularInline): 
    model = Bar 
    form = BarForm 

@admin.register(Foo) 
class FooAdmin(admin.ModelAdmin): 
    model = Foo 
    inlines = [BarInline,] 

forms.py

class BarForm(forms.models.ModelForm): 
    class Meta: 
     model = Bar 
     fields = ('name',) 

    def clean(self): 
     data = self.cleaned_data  
     if not item['name'].startswith('Bar'): 
     raise ValidationError('Item is not valid.') 

所以我沒有用InlineFormSet和我根本沒有使用inlineformset_factory,這是一個完整的解決方案,不僅可以處理由未經測試的搜索帶來的片段

+0

我想知道這與我所建議的有何不同。 – Wtower

1

要添加驗證您的在線表單集,你可以創建自定義表單,並指定此表格表單集,而不是創建自定義的基本在線表單集:

class MyForm(forms.ModelForm): 
    def clean(self): 
     cleaned_data = super(MyForm, self).clean() 
     for field in cleaned_data: 
      # if some meaningful condition for field is met: 
       # raise validation error 
     return cleaned_data 

    class Meta: 
     model = ParentModel 
     fields = ['fieldA', 'fieldB', ...] 

BarInlineFormset = inlineformset_factory(ParentModel, Model, form=MyForm, extra=0, min_num=0) 

不要忘記正確配置你的模型表單,特別是它的元類來定義模型和字段。

參考:Django documentation: Model form FunctionsCreating forms from models

+0

親愛的@serjik,這僅僅是一個關於您所問問題的代碼示例,而不是如何構建模型。你需要爲模型定義一個元。我建議你閱讀關於表單的文檔。 – Wtower