[英]Override django-taggit tags so that they are always lowercase
I couldnt find a good answer or solution for multiple tags in a model.我无法为模型中的多个标签找到好的答案或解决方案。 the only thing I found close was this:
我发现唯一接近的是:
How can I limit django-taggit to accept only lowercase words? 如何限制 django-taggit 只接受小写单词?
here is my current code:这是我当前的代码:
from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase
class TaggedStory(TaggedItemBase):
content_object = models.ForeignKey("Story")
class TaggedSEO(TaggedItemBase):
content_object = models.ForeignKey("Story")
class Story(models.Model):
...
tags = TaggableManager(through=TaggedStory, blank=True, related_name='story_tags')
...
seo_tags = TaggableManager(through=TaggedSEO, blank=True, related_name='seo_tags')
I usually implement this at the form level:我通常在表单级别实现这个:
def clean_tags(self):
"""
Force all tags to lowercase.
"""
tags = self.cleaned_data.get('tags', None)
if tags:
tags = [t.lower() for t in tags]
return tags
It really depends on how you look at it.这真的取决于你如何看待它。 I'm happy with solution because I consider it a validation problem.
我对解决方案很满意,因为我认为这是一个验证问题。 If you consider it a data integrity problem, I can understand why you'd want to do it at the model level.
如果您认为这是一个数据完整性问题,我可以理解您为什么要在模型级别执行此操作。 At which point your best bet is to subclass the taggit modules to a point that you can override Tag.save().
此时最好的办法是将 taggit 模块子类化到可以覆盖 Tag.save() 的点。
In the appname --> utils file, for eg:(blog --> init .py), define a function as follows:在 appname --> utils 文件中,例如:(blog --> init .py),定义一个函数如下:
def comma_splitter(tag_string): """convert each tag into lowercase""" return [t.strip().lower() for t in tag_string.split(',') if t.strip()] defcomma_splitter(tag_string): """将每个标签转换成小写""" return [t.strip().lower() for t in tag_string.split(',') if t.strip()]
And then, in the settings.py file, define and override the default taggit settings as: TAGGIT_TAGS_FROM_STRING = 'blog.然后,在 settings.py 文件中,将默认 taggit 设置定义并覆盖为: TAGGIT_TAGS_FROM_STRING = 'blog. init .comma_splitter'
init .comma_splitter'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.