Django Taggit rendering tags as object in custom form

677 views Asked by At

Duplicate question to Django-Taggit in Edit Form. However, the answer doesn't work for me.

I'm using Django Taggit in a form. The form is populated by an instance of an object that has Django Taggit enabled.

In my template, the forms tag input field value is set like so:

value="{{ form.tags.value|default_if_none:"" }}"

This results in a string value in the rough format of:

value="[<TaggedItem: foo tagged with bar>]"

If I render the form using basic Django form rendering ( i.e. {{form}} ), the tag field value is rendered correctly ( i.e. "tag1, tag2" ). Strangely, this is the opposite to what the poster of Django-Taggit in Edit Form was experiencing. For them, {{ form }} wasn't rendering the value correctly, but for me, it is.

Why is there this difference between my form and Django's? How can I make the tag value render correctly in my custom form template?

1

There are 1 answers

0
Jack On

I have a solution that feels hacky but works.

When instantiating the form, modify the initial state for the tags:

form = YourModelForm(request.POST or None, instance=your_model_instance, initial={
    'tags' : edit_string_for_tags(your_model_instance.tags.get_query_set())
})

edit_string_for_tags() and get_query_set() are part of Django Taggit.

Note: You'll need to import edit_string_for_tags(). i.e. from taggit.utils import edit_string_for_tags