Limit Maximum Choices of ManyToManyField

后端 未结 3 1309
清酒与你
清酒与你 2021-02-20 16:51

I\'m trying to limit the maximum amount of choices a model record can have in a ManyToManyField.

In this example there is a BlogSite that can be related to Regions. In t

3条回答
  •  遥遥无期
    2021-02-20 17:41

    Working! I have used this and its working properly. Validation required before saving the data. So you can use code in form

    class BlogSiteForm(forms.ModelForm):
        def clean_regions(self):
            regions = self.cleaned_data['regions']
            if len(regions) > 3:
                raise forms.ValidationError('You can add maximum 3 regions')
            return regions
        class Meta:
            model = BlogSite
            fields = '__all__'
    

提交回复
热议问题