Django + Ajax投票

时间:2015-06-29 10:05:17

标签: jquery python ajax json django

我正在尝试按照outdated answer关于如何使用ajax添加UpVoting(与关于喜欢的原始答案不同)。服务器运行没有错误,但是当我单击ajax按钮时没有任何反应。任何想法哪些部分不起作用(之前没有使用过jquery)?

models.py

class Recommendation(models.Model):
    topic = models.ForeignKey(Topic)
    user = models.ForeignKey(User)
    title = models.CharField(max_length=300)
    description = models.TextField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    votes = VotableManager()

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse(viewname="recommendation_edit", args=[self.topic.id])


    def get_total_votes(self):
        total = self.votes.count()
        return int(total)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Recommendation, self).save(*args, **kwargs)

urls.py

url(r'^upvote/$', 'core.views.upvote', name='upvote'),

views.py

@login_required
@require_POST
def upvote(request):
    if request.method == 'POST':
        user = request.user
        slug = request.POST.get('slug', None)
        recommendation = get_object_or_404(Recommendation, slug=slug)

        if recommendation.votes.filter(id=user.id).exists():
            # user has already liked this company
            # remove like/user
            recommendation.votes.remove(user)
            message = 'You disliked this'
        else:
            # add a new like for a company
            recommendation.votes.up(user)
            message = 'You liked this'

    ctx = {'recommendations_count': recommendation.get_total_votes, 'message': message}
    # use mimetype instead of content_type if django < 5
    return HttpResponse(json.dumps(ctx), content_type='application/json')

recommendation.html(这包含在另一个模板文件中)

<div class="row">
    <hr>
 <div class="col-md-8">
 <h2>{{ recommendation.title }}</h2>
 </div>

 <div class="col-md-4 text-right">
 <h4><a class="subheading"> {{ recommendation.created_at | date }}</a></h4>
 <h4>{{ recommendation.user.get_full_name }} </h4>
 </div>

</div>
<p>{{ recommendation.description }}</p>-

<p> Vote Count: {{ recommendation.get_total_votes }}</p>

<p>Upvote Button:</p>
<input type="button" id="upvote" name="{{ recommendation.id }}" value="Upvote" />

<script>
$('#upvote').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'upvote' %}",
               data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert('Recommendations upvotes count is now ' + response.get_total_votes);
                },
                error: function(rs, e) {
                       alert(rs.responseText);
                       alert('ERROR');
                }
          }); 
    })
</script>

使用votes app来处理投票。

0 个答案:

没有答案