像列表上的按钮一样,按效果始终位于第一个

时间:2019-01-24 20:22:31

标签: javascript python jquery ajax django

我的问题是:

  1. 我无法显示已被选择的按钮(“向上投票”或“向下投票”)-视图代码中的变量。
  2. 当我按下最后一条评论的按钮时,例如“投票”。 -第一个评论上的“投票”按钮会突出显示-不会进行排序。

问题可能是这是一个列表,并且在视图中,对象已经是Post模型。

我的代码在下面。

这是帖子和评论的模型

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = RichTextUploadingField()
    votes_up = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='up_votes')
    votes_down = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='down_votes')

    def __str__(self):
        return self.text

    def total_vote_up(self):
        return self.votes_up.count()

    def total_vote_down(self):
        return self.votes_down.count()


class Comment(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    text = RichTextUploadingField()

这是详细视图,我想在其中查看是否喜欢评论。我传递到上下文变量。

class PostDetail(generic.DetailView, FormMixin):
    template_name = 'post_detail.html'
    context_object_name = 'post'
    model = Post
    form_class = CommentForm

    def get_context_data(self, **kwargs):
        is_voted_up = False
        is_voted_down = False

        comments = self.get_object().comments.all()
        for comment in comments:
            if answer.votes_up.filter(id=self.request.user.id).exists():
                print(answer)
                is_voted_up = True
                print(is_voted_up)
            if answer.votes_down.filter(id=self.request.user.id).exists():
                is_voted_down = True

        context = super(PostDetail, self).get_context_data(**kwargs)
        context['comments'] = comments
        context['form'] = CommentForm(initial={'post': self.get_object(), 'author': self.get_user()})
        context['is_voted_up'] = is_voted_up
        context['is_voted_down'] = is_voted_down
        return context

以下是要投票赞成或反对的网址和视图:

url(r'^voteup/$', login_required(CommentVoteUpView.as_view()), name='comment_voteup'),
url(r'^votedown/$', login_required(CommentVoteDownView.as_view()), name='comment_votedown'),


class CommentVoteUpView(generic.View):
    def post(self, request):
        comment = get_object_or_404(Comment, id=request.POST.get('id'))
        is_voted_up = False
        if comment.votes_up.filter(id=request.user.id).exists():
            comment.votes_up.remove(request.user)
            is_voted_up = False
        else:
            comment.votes_up.add(request.user)
            is_voted_up = True
        context = {
            'comment': comment,
            'is_voted_up': is_voted_up,
            'total_vote_up': comment.total_vote_up(),
            }
        if request.is_ajax():
            html = render_to_string('voteup_section.html', context, request=request)
            return JsonResponse({'form': html})


class CommentVoteDownView(generic.View):
    def post(self, request):
        comment = get_object_or_404(Comment, id=request.POST.get('id'))
        is_voted_down = False
        if comment.votes_down.filter(id=request.user.id).exists():
            comment.votes_down.remove(request.user)
            is_voted_down = False
        else:
            comment.votes_down.add(request.user)
            is_voted_down = True
        context = {
            'comment': comment,
            'is_voted_down': is_voted_down,
            'total_vote_down': comment.total_vote_down(),
            }
        if request.is_ajax():
            html = render_to_string('votedown_section.html', context, request=request)
            return JsonResponse({'form': html})

下面是jquery代码:

        <script type="text/javascript">
            $(document).ready(function(event){
                $(document).on('click', '#voteup', function(event){
                    event.preventDefault();
                    var pk = $(this).attr('value');
                    $.ajax({
                        type: 'POST',
                        url: "{% url 'comment_voteup' %}",
                        data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                        dataType: 'json',
                        success: function(response){
                            $('#voteup-section').html(response['form'])
                            console.log($('#voteup-section').html(response['form']))
                        },
                        error: function(rs, e){
                            console.log(rs.responseText);
                        },
                    });
                });
            });
        </script>

        <script type="text/javascript">
            $(document).ready(function(event){
                $(document).on('click', '#votedown', function(event){
                    event.preventDefault();
                    var pk = $(this).attr('value');
                    $.ajax({
                        type: 'POST',
                        url: "{% url 'comment_votedown' %}",
                        data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                        dataType: 'json',
                        success: function(response){
                            $('#votedown-section').html(response['form'])
                            console.log($('#votedown-section').html(response['form']))
                        },
                        error: function(rs, e){
                            console.log(rs.responseText);
                        },
                    });
                });
            });
        </script>

最后但并非最不重要的html部分-仅注释部分和投票部分的按钮:

          {% if comment %}
              <h5>{{ comment.count }} Answers:</h5>
              <hr>
              {% for comment in comments %}
              <div class="media mb-4">
                <img class="d-flex mr-3 rounded-circle" src="http://placehold.it/50x50" alt="">
                <div class="media-body">
                    <h5 class="mt-0">{{ comment.author }}</h5>
                    <p>{{ comment.text|safe }}</p>
                    <div class="btn-group btn-group-sm">
                        <div id="voteup-section">
                            {% include 'voteup_section.html' %}
                        </div>
                        <div id="votedown-section">
                            {% include 'votedown_section.html' %}
                        </div>
                    </div>
                </div>
              </div>
              {% if not forloop.last %}
              <hr>
              {% endif %}
              {% endfor %}
          {% endif %}

投票按钮:

<form action="{% url 'comment_voteup' %}" method="post">
    {% csrf_token %}
    <button type="submit" id="voteup" name="comment_id" value="{{ comment.id }}" {% if is_voted_up %} class="btn btn-danger btn-sm">Voted up! {% else %} class="btn btn-primary btn-sm">Vote up!{% endif %} <span class="badge badge-light">{{ total_vote_up }}</span></button>
</form>

我希望您能够对“投票”或“投票”的每条评论进行投票,并知道选择了哪个按钮或“投票”或“投票”。

1 个答案:

答案 0 :(得分:1)

如果DOM具有多个具有相同id的元素,则任何代码如下:

$(#some_repeated_id)

将使用id=some_repeated_id引用第一个元素。话虽如此,我会建议一些更改:

<!-- div id="voteup-section" -->
<div id="voteup-section-{{ comment.id }}">

并采用

格式
<!--button type="submit" id="voteup-{{ comment.id }}" name="comment_id" value="{{ comment.id }}" {% if is_voted_up %} class="btn btn-danger btn-sm">Voted up! {% else %} class="btn btn-primary btn-sm">Vote up!{% endif %} <span class="badge badge-light">{{ total_vote_up }}</span></button-->

<button type="submit" id="voteup-{{ comment.id }}" name="comment_id" value="{{ comment.id }}" {% if is_voted_up %} class="btn btn-danger btn-sm">Voted up! {% else %} class="btn btn-primary btn-sm">Vote up!{% endif %} <span class="badge badge-light">{{ total_vote_up }}</span></button>

然后使用data-*属性处理正确的按钮,以在javascript中单击。