我试图验证变量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的相同值的解决方案。任何建议都表示赞赏。
答案 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"]})