【问题标题】:django-taggit custom 'tag' model and request.userdjango-taggit 自定义“标签”模型和 request.user
【发布时间】:2013-10-14 10:41:32
【问题描述】:

我需要跟踪标签的创建时间和创建者,因此像这样使用 django-taggit 创建了自定义标签模型

class Topics(TagBase):
    featured = models.BooleanField(_('Featured'), default=False)

    created = models.DateTimeField(_('Creation date'), auto_now_add=True, editable=False)
    created_by = models.ForeignKey(User, related_name="topic_created_by")


class ArticleTopic(ItemBase):
    content_object = models.ForeignKey('Article')
    tag = models.ForeignKey(Topics, related_name="topic_items")


class Article(models.Model):   
    title = models.CharField(_('Title'), max_length=255)

    excerpt = models.TextField(_('Excerpt'))
    content = models.TextField(_('Content'), blank=True)

    topics = TaggableManager(through=ArticleTopic)

    created = models.DateTimeField(_('Creation date'), auto_now_add=True, editable=False)
    created_by = models.ForeignKey(User, related_name="article_created_by")

我正在使用 django-autocomplete-light 在管理员中为主题创建一个自动完成字段,并在保存文章表单时输入一个新主题。

虽然我知道我可以在管理表单中获取 request.user 并通过 save_model 方法传递它 - 这是我为 Article 模型所做的 - 我不知道如何为 Topics 模型执行此操作.

提前致谢

【问题讨论】:

  • 也许在 clean_tags 中?
  • @jpic 不是。那是在保存文章之前,主题需要文章实例来生成关系。我必须在那里重新创建 taggit 的 TaggableManager() 功能 - 假设这是可能的。

标签: python django django-taggit django-autocomplete-light


【解决方案1】:

我遇到了类似的问题,并分叉了 django-taggit 来添加这个功能:https://github.com/professorplumb/django-taggit

您可以像这样为自定义的 through 或 tag 模型添加属性:

article.topics.add('topic1', 'topic2', created_by=request.user)

【讨论】:

  • 这似乎正是我所需要的。谢谢!但是,我无法让它工作。错误是companies.companytype: 'topics' is a manually-defined m2m relation through model CompanyTopic, which does not have foreign keys to Topics and CompanyType,我认为它与attname 有关,但我不知道在哪里设置它。
  • 如果有帮助,我正在使用GenericTaggedItemBase
  • 搞定了。切换回稳定版本并包含您的提交。无法说出开发版本中发生了哪些变化,这些变化与我的代码不匹配,但将来需要处理。
  • 我有一个关于 django-taggit 的问题,你能帮帮我吗? stackoverflow.com/questions/39574909/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 1970-01-01
  • 2014-11-15
  • 2012-03-24
  • 2017-10-14
  • 1970-01-01
相关资源
最近更新 更多