Frage

I'm trying to work with m2m fields.

What I want to do is to have a string (CharField) where user can write the tags of a post, with each tag separated by commas.

I was able to do the creation in this way:

  tags = tags.split(',')
        for tag in tags:
            obj, create = Tag.objects.get_or_create(name=tag)
            pub.tags.add(obj)

Now, I want to do the UpdateView. Obviously if I don't specify the conversion from list to string in the form, I don't have any value set. So it should be something like:

for tag in tags:
    str+=tag+","

The point is:

  • Do I have to write the conversion of list to string and string to list each time?
  • Can i specify somewhere how to do this conversion? Is there anything already implemented in Django?

PS: In the UpdateView, if I remove a tag, how can I remove it from the relation as well since I have to do the parsing by hand?

Thanks.

War es hilfreich?

Lösung

The simplest way is to remove all the tags from pub.tags first, then add them all back in:

# Clear the existing tags
pub.tags.clear()

tags = tags.split(',')
for tag in tags:
    obj, create = Tag.objects.get_or_create(name=tag)
    pub.tags.add(obj)

Instead of looping and building a String, you might try this more pythonic method:

tags = ['red', 'green', 'blue'] ','.join(tags) 'red,green,blue'

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top