I am using ManyToMany relationship in my code in a scenario where i have showrooms and their categories. Now a showroom can fall into maximum three categories and i have to validate it while saving. Below is my code:
##models.py
class Showrooms(models.Model):
    name = models.CharField(max_length = 100)
    contact_person = models.CharField(max_length = 100)
    offer = models.TextField()
    categories = models.ManyToManyField(Categories, null=True, blank=True,    related_name='categories')
    class Meta:
        db_table = 'showrooms'
        verbose_name_plural = "showrooms"
class Categories(models.Model):
    category = models.CharField(max_length = 100)
    image = models.ImageField(upload_to = showroom_upload_path, null=True, blank=True)
    slug = models.SlugField(blank=True)
    class Meta:
        db_table = 'showroom_categories'
        verbose_name_plural = "categories"
    def __str__(self):
        return self.category
everything is working fine except i am not able to put validation on number of categories per showroom. And i am not using it in views but just wanna to do it in admin.
Please help
Thanks
Ok.. I have solved my issue. I created a form in forms.py
class ShowroomsForm(forms.ModelForm):
    class Meta:
        model = Showrooms
    def clean(self):
        categories = self.cleaned_data.get('categories')
        if categories and categories.count() > 3:
            raise ValidationError('Maximum three categories are allowed.')
        return self.cleaned_data
and added it to admin.py like below:
class ShowroomsAdmin(admin.ModelAdmin):
    form = ShowroomsForm
admin.site.register(Showrooms, ShowroomsAdmin)
You could define a clean() method on your model an raise a validation error whenever a showroom gets assigned to more than 3 categories.
https://docs.djangoproject.com/en/1.5/ref/models/instances/#django.db.models.Model.clean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With