Using Mongoengine and trying to form a tag cloud. To each item I would like to attach one or more tags. Something similar like the tags are used here (below each question asked).
After searching and reading many posts here, I still can't the proper way of adding new entries to a ListField, or how to replace them.
class Item(Document):
tags = ListField(StringField(max_length=300))
I'm trying to push one or more new tags, by using a form and gather the posted results. In my views.py I have the following check:
if 'tags' in request.POST and request.POST['tags'] <> '':
for Tag in request.POST.getlist('tags'):
ItemData.update(push__tags__S__tags=Tag)
When trying to push it, it fails:
ValidationError (Profile:5185505b73ea128e878f4e82) (Only lists and tuples may be used in a list field: ['tags'])
Obviously I'm using the wrong type, but I'm lost on how to get this one solved. Strange thing is that for some reason the data is appended to the record though.. (posted "test" and refreshed browser)
"tags" : [ "test", "test" ] }
Can one show me a small example how to deal with a posted string (from a HTML form) and push it properly into a ListField (and how to replace them all).
Thanks!
You don't need the positional operator $
which equates to __S__
in mongoengine as you aren't replacing / updating a position in the list.
As you probably don't want to repeat the tags, you should use $addToSet. You can do this in mongoengine like so:
ItemData.update(add_to_set__tags=['tag1', 'tag2'])
Passing in a list to add_to_set
will automatically convert it to an $addToSet
with $each
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With