开发者

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

开发者 https://www.devze.com 2023-03-17 09:11 出处:网络
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 fin开发者_如何转开发d a way to set a maximum numb

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 fin开发者_如何转开发d 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


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


The TaggableManager uses an internal _TaggableManager that has an add method that you'll need to change.

First, you'll need to extend _TaggableManager and change the add method to check how many tags are being used, and modify the list of tags accordingly.

Then you'll have to extend TaggableMananger and override __get__ so that it uses your custom _TaggableManager.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号