10

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

Edits

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)
Rakesh Kumar
  • 157
  • 1
  • 13

3 Answers3

6

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

Adrien
  • 640
  • 4
  • 11
  • I tried that but it was showing errors. Logically, to validate categories first we need to have a showroom object which is not possible without saving it. IMO form would be a better place. What do you think? – Rakesh Kumar Feb 04 '14 at 09:26
  • 1
    Hey.. I have solved my issue. I have edited my question to show the answer. It was very easy :) BTW thanks for your time and help – Rakesh Kumar Feb 04 '14 at 09:33
  • 3
    @RaakeshKumar Go ahead and answer your own question, this is highly encouraged. That way we can upvote the answer and compare it to other answers, and this question will be considered answered by the site. – Flimm Dec 23 '16 at 13:13
0

I had the same problem and used @Rakesh Kumar's solution. But then I got an error

django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form JobsForm needs updating.

The problem was that Rashid's form didn't have any form fields. So I modified his solution just a little.

forms.py - I added fields

class ShowroomsForm(forms.ModelForm):
    class Meta:
        model = Showrooms
        fields = "__all__"
    
    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

admin.py - this remained the same:

class ShowroomsAdmin(admin.ModelAdmin):
    form = ShowroomsForm
    

admin.site.register(Showrooms, ShowroomsAdmin)

After that, it worked perfectly!

sajeyks mwangi
  • 549
  • 8
  • 20
-1

All I needed was to create a model form:

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)
Rakesh Kumar
  • 157
  • 1
  • 13