【问题标题】:Override django-taggit tags so that they are always lowercase覆盖 django-taggit 标记,使它们始终为小写
【发布时间】:2014-09-05 00:30:07
【问题描述】:

我无法为模型中的多个标签找到好的答案或解决方案。我发现唯一接近的是:

How can I limit django-taggit to accept only lowercase words?

这是我当前的代码:

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')

【问题讨论】:

    标签: python django django-taggit


    【解决方案1】:

    我通常在表单级别实现这个:

    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
    

    这真的取决于你如何看待它。我对解决方案很满意,因为我认为这是一个验证问题。如果您认为这是一个数据完整性问题,我可以理解您为什么要在模型级别执行此操作。此时最好的选择是将 taggit 模块子类化到可以覆盖 Tag.save() 的程度。

    【讨论】:

    • 好电话,我什至没有想过在表格上检查它。我可以试试这个,我只是无法将其子类化。
    【解决方案2】:

    在appname --> utils文件中,例如:(blog --> init.py),定义一个函数如下:

    def comma_splitter(tag_string): """将每个标签转换为小写""" return [t.strip().lower() for t in tag_string.split(',') if t.strip()]

    然后,在 settings.py 文件中,定义并覆盖默认的 taggit 设置: TAGGIT_TAGS_FROM_STRING = 'blog.init.comma_splitter'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多