سؤال

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)
هل كانت مفيدة؟

المحلول 3

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)

نصائح أخرى

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

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!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top