Search code examples
pythondjangotagsdjango-taggit

How can you limit the maximum number of tags an object can have in django-taggit?


I've been really impressed with the implementation of django-taggit as an application for handling tags within Django. However, I have been unable to find a way to set a maximum number of tags which can be applied to an object - a 'MAX_TAG' if you will. Is this possible? I'd like to limit my application to, for example, only 5 tags per object.

Thanks,

J


Solution

  • I've solved this in the admin model:

    class MyObjectAdminForm(forms.ModelForm):
        class Meta:
            model = MyModel
    
        def clean_tags(self):
            tags = self.cleaned_data['tags']
            if len(tags) > 3:
                raise ValidationError("....")
            return tags
    
    class MyObjectAdmin(admin.ModelAdmin):
        form = MyObjectAdminForm