Django自定义按钮计数器

时间:2017-03-02 19:52:50

标签: django python-2.7 django-models django-templates django-views

我希望在每个帖子的底部都有2个按钮:

buttons

我需要建议如何实现这一目标。我试过django-vote库,但它对我不起作用。

我的代码:

<--template.html-->
<div class="post-bottom overflow">
   <ul class="nav navbar-nav post-nav">
       <li><a href="#"><i class="fa fa-tag"></i>0 Creative</a></li>
       <li><a href="#"><i class="fa fa-heart"></i>32 Love</a></li>
   </ul>
</div>

_

###**VIEWS.PY**###
class IndexView(generic.ListView):
   template_name = 'web_serv/index.html'
   context_object_name = 'post_list'
   paginate_by = 10

   def get_queryset(self):
       queryset = Post.objects.all()

       if self.request.GET.get('category'):
           queryset = queryset.filter(category=self.request.GET.get('category', ''))
       return queryset

   def get_context_data(self, **kwargs):
       context = super(IndexView, self).get_context_data(**kwargs)
       context['category_list'] = Category.objects.all()
       return context

_

#models.py#
class Post(VoteModel, models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=40)
    category = models.ForeignKey(Category)
    picture = ImageWithThumbsField(sizes=((850, 400), (66, 66)))
    content = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['-created_date']

    def __str__(self):
        return self.title + ' - ' + str(self.created_date.date())

欢迎任何建议:)

1 个答案:

答案 0 :(得分:3)

你要问的是一些工作,所以这是粗略的轮廓。如果您还要添加PostLove,也可以复制PostCreative

<强> models.py

class PostLove(models.Model):
    user = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='postlovesAsUser')
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='postlovesAsPost')
    total_loves = models.IntegerField(default=0)

    def __str__(self):
        return '{0}'.format(self.post.title)

<强> views.py

class PostLoveView(View):
    def post(self, request):
        data = {}
        user = request.user

        post_id = int(request.POST['post_id'])
        post = get_object_or_404(Post, id=post_id)

        loved, created = PostLove.objects.get_or_create(post=post)

        user_loved = get_object_or_none(PostLove, user=user, post=post)

        if user_loved:
            loved.user.remove(user)
            PostLove.objects.filter(post=post).update(total_loves=F('total_loves')-1)
            data['success'] = 'unloved'
        else:
            loved.user.add(user)
            PostLove.objects.filter(user=user, post=post).update(total_loves=F('total_loves')+1)
            data['success'] = 'loved'

        return JsonResponse(data)

<强> urls.py

url(r'^post-love/$', views.PostLoveView.as_view(), name='post_love'),

<强> HTML

<div class="post-bottom overflow">
   <ul class="nav navbar-nav post-nav">
       <li><a href="#"><i class="fa fa-tag"></i>0 Creative</a></li>
       <li><a id="love-button" data-post-id="{{ post.id }}" href="#"><i class="fa fa-heart"></i><span id="love-count">32</span> Love</a></li>
   </ul>
</div>

<强>的javascript

$("#love-button").click(function(e) {
  e.preventDefault();

  var $this = $(this),
      postID = $this.data('post-id'),
      $totalLoves = $('#love-count'),
      total = parseInt($totalLoves.html()),;

  $.ajax({
    type: "POST",
    url: "{{ url 'post_love' }}",
    data: {"post_id": postID}
  })
  .done(function(response) {
    alert("Success")

    var is_loved = JSON.parse(response)['success'];

    if (is_loved == "loved") {
        $totalLoves.html(total + 1);
    } else if (is_loved = "unloved") {
        $totalLoves.html(total - 1);
    }

  })
  .fail(function() {
    alert("Failure")
  })
})

然后,您可以迁移数据库以创建新模型,并且应该完成。