2

I have a requirement to track when and by whom a tag was created and so have created a custom tag model using django-taggit like so

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

I'm using django-autocomplete-light to create an autocomplete field for Topics in the admin and typing in a new Topic creates it on saving the Article form.

While I know I can get request.user in the admin form and pass it thru the save_model method - which is what I'm doing for the Article model - I can't figure out how to do so for the Topics model.

Thanks in advance

affan
  • 56
  • 6
  • Maybe in clean_tags ? – jpic Jan 16 '14 at 01:08
  • @jpic Not really. That's before the Article is saved and the Topic needs the Article instance to generate the relation. I'd have to recreate taggit's TaggableManager() functionality within there - assuming that's even possible. – affan Jan 16 '14 at 09:29

1 Answers1

2

I ran into a similar problem and forked django-taggit to add this functionality: https://github.com/professorplumb/django-taggit

You add attributes for a custom through or tag model like so:

article.topics.add('topic1', 'topic2', created_by=request.user)
Eric P
  • 4,587
  • 6
  • 24
  • 19
  • This appears to be exactly what I need. Thanks! However, I can't get it to work. The error is `companies.companytype: 'topics' is a manually-defined m2m relation through model CompanyTopic, which does not have foreign keys to Topics and CompanyType` and I think it has to do with the `attname` but I have no idea where to set it. – affan Mar 11 '14 at 12:27
  • I'm using `GenericTaggedItemBase` if that helps – affan Mar 11 '14 at 13:40
  • Got it working. Switched back to the stable version and included your commit. Unable to say what's changed in the develop version that's not playing nice with my code but something to deal with in the future. – affan Mar 11 '14 at 14:31
  • I had a problem about django-taggit, could you help me ? https://stackoverflow.com/questions/39574909/filter-tags-of-django-taggit-in-djangos-queryset – polar9527 Sep 21 '16 at 13:06