Django:TypeError:'Like'对象不可迭代(Ajax请求)

时间:2014-02-27 13:52:57

标签: ajax django iterable

我没有得到关于Model(Like)对象不可迭代的清晰图片。

错误

liked, created = Like.objects.create(question=create_id)
TypeError: 'Like' object is not iterable

model.py

class Question(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length= 200)
    description = models.TextField()
    location = models.CharField(max_length=150)
    tags = TaggableManager()
    time = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.title


class Like(models.Model):
    user = models.ManyToManyField(User, related_name='likes')
    question = models.ForeignKey(Question)
    date = models.DateTimeField(auto_now_add=True)
    likecount = models.IntegerField(default=0)

urls.py

 url(r'^like/$', 'apps.question.views.like', name='like'),

views.py

def like(request):
    vars = {}
    if request.method == 'POST':
        user = request.user
        tutorial_id = request.POST.get('tutorial_id', None)
        create_id = get_object_or_404(Question, id=tutorial_id)

        liked, created = Like.objects.create(question=create_id)

        try:
            user_liked = Like.objects.get(question=create_id, user=user)
        except:
            user_liked = None

        if user_liked:
            user_liked.likecount -= 1
            liked.user.remove(request.user)
            user_liked.save()
        else:
            liked.user.add(request.user)
            liked.likecount += 1
            liked.save()

    return HttpResponse(simplejson.dumps(vars, user),
                    mimetype='application/javascript')

模板

<button type="button" class="btn btn-request" name="{{question.id}}" id="like">Request</button>

<script>
  $('#like').click(function(){

        $.ajax({
                 type: "POST",
                 url: "{% url 'like' %}",
                 data: {'tutorial_id': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},

                 dataType: "text",
                 success: function(response) {
                        alert('You liked this')
                  },
                  error: function(rs, e) {
                        alert(rs.responseText);
                  }
            }); 
      })
  </script>

我在这里缺少什么,有人可以解释一下吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

Like.objects.create(question=create_id)

返回单个对象(Like)。

因此,执行like, created = Like.objects.create(question=create_id)不起作用,因为右侧只有一个项目,因此无法解压缩(如果您执行了like, created = 1)。

返回对象和created布尔对象的方法是get_or_create

like, created = Like.objects.get_or_create(question=create_id)