我正在尝试使用TaggableManager()在django应用程序中添加我的表单中的标签,但这似乎不起作用。
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)
我的html模板:
<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()
当我点击此查询时
UserBookmark.objects.filter(tag__name__in = ['java'])
我得到空集, 虽然我有这个标签java的记录。
之前我的UserBookmark
模型标记属性为CharField
:
tag = models.CharField(max_length = 100)
但是这不起作用,因为标签有很多关系,因为书签可以有很多标签,所以CharField不起作用。
有人可以告诉我这里需要纠正什么吗?
答案 0 :(得分:1)
您必须使用 add()
在ManyToMany字段中添加项目
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()
现在您的查询工作正常。