在django admin中显示m2m_changed信号的验证错误

时间:2016-07-03 06:17:27

标签: python django django-admin django-signals django-validation

我试图验证变量foo对于MyModel和Item是相同的,然后将其添加为m2m。如果不是,我想在管理员中引发ValidationError。

models.py

>>> xxx='Juliana Gon\xe7alves Miguel'
>>> t=re.sub('\w*','',xxx)
>>> t
' \xe7 '

signals.py

class Item(models.Model):
    foo = models.CharField(max_length=200)    

class MyModel(models.Model):
    foo = models.CharField(max_length=200)
    items = models.ManyToManyField(Item)

ValidationError是否有办法在管理员中正确显示而不是500错误。

我无法提出使用MyModel的干净方法来验证foo的相同值的解决方案。任何建议都表示赞赏。

1 个答案:

答案 0 :(得分:2)

使用form方法创建clean类,并修改您的管理类以使用该表单。阅读this

像:

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    search_fields = ('foo', 'items__foo')
    list_display = ('foo', 'items__foo')
    form = MyModelForm


class MyModelForm(forms.ModelForm):

    def clean(self):
        """
        This is the function that can be used to 
        validate your model data from admin
        """
        super(MyModelForm, self).clean()
        foo = self.cleaned_data.get('foo')
        pk_set = Item.objects.all().values_list("id")

        # The logic you were trying to filter..
        if Item.objects.filter(id__in=pk_set).count() != len(pk_set):
            raise ValidationError({'items': ["Foo doesn't match"]})