开发者

error_messages for ManyToManyField in ModelForm

I have model with ManyToManyField field. I also have ModelForm that uses this model.

How to define error_messages for such field?

Example:

class Article(models.Model):
    categories = models.ManyToManyField(Category)

class Article开发者_C百科Form(ModelForm):
    class Meta(ContentForm.Meta):
        model = Article

I want to override 'required' error message for categories field in ArticleForm model.

I was Googling about this problem but all solutions not work either they are not form ModelForm or for ManyToManyField.


You could try to do your own validation for this field. In model set for m2m field blank=True, and in form implement clean_categories method. If field categories is not valid, raise exception with your content.

In model:

categories = models.ManyToManyField(Category, blank=True)

In form:

def clean_categories(self):
    if not self.cleaned_data.get('categories'):
        raise forms.ValidationError('My custom message')
    return self.cleaned_data['categories']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜