0

I am trying to use TaggableManager() to add tags in my form in django application but this does not seem to work.

class UserBookmark(models.Model):

    user = models.ForeignKey(User)
    bookmark = models.URLField()
    tag = TaggableManager()

    def __str__(self):
        return '%i %s %s'%(self.id,self.user,self.bookmark)

my html template:

<div class="modal-body">
   <form name = "form2" id = "form2" method = "post" action = "{% url 'savetag' %}" class = "form-inline">
      {% csrf_token %}
      <div class = "form-group">
         <input name = "tag"  id = "tag" required>
         <input type="hidden" id = "field1" name="bookmark" value="">
         <button type = "submit" class = "btn btn-danger">Save</button>
      </div>
   </form>
</div>

views.py :

def save_tag(request):

    tagslist = request.POST.getlist("tag")
    bookmark = request.POST.get("bookmark")
    obj=UserBookmark.objects.get(bookmark = bookmark)
    user = request.user.pk
    obj.tag = tagslist
    obj.save()

when i hit this query

UserBookmark.objects.filter(tag__name__in = ['java'])

I get empty set, while i do have records with this tag java.

earlier my UserBookmark model tag attribute was CharField:

tag = models.CharField(max_length = 100)

but this did not work because tag had a many to many relationship as a bookmark can have many tags, so CharField did not work.

Can someone tell me what needs to be corrected here?

Satendra
  • 6,755
  • 4
  • 26
  • 46
Dhruv Pandey
  • 482
  • 6
  • 18

1 Answers1

2

You have to use add() to add item in ManyToMany field

def save_tag(request):
   # Use get() instead of getlist() beacuse in request it is a string 'Python,Data Science' not array
   tagslist = request.POST.get("tag")
   # Use split to make it a list
   tagslist = [str(r) for r in taglist.split(',')]
   ...
   # use add to add item in ManyToMany field.
   obj.tag.add(*tagslist)
   obj.save()

Now your query will work fine.

Satendra
  • 6,755
  • 4
  • 26
  • 46