首页 > 解决方案 > Upvote 动作正在为所有卡片执行 django

问题描述

<div  style="margin-left: 10px;margin-right: 10px;">

  <div class="card-columns" >
    {% for marking in marking_maestro %}
    <div class="card ">
      <img class="card-img-top" src=""  alt="Card image cap">
      <div class="card-body">
        <h5 class="card-title" name="title">{{marking.product_title}}</h5>
        <h5 class="card-title" name="title">{{marking.id}}</h5>
        <p class="card-text">Random text</p>
        <br>

        <div  class="row" >
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-modal-lg-1">View more</button>
        &emsp;
        <a href="{% url 'invest' pk=marking.id %}";><button type="submit" class="btn btn-primary" data-toggle="modal" >Invest</button></a>
      </div>
      <br>
      <form method="POST" id="post-invest">
        {% csrf_token %}
        <div  class="row" >
            <input class="btn btn-outline-secondary" id="upvote_button" type="submit" name="upvote" value="upvote">
        </div>
    </form>
    </div>
    <!-- for upvote -->
    <script>
      // upvote
  $(document).on('submit', '#post-invest',function(e){
      e.preventDefault();
      // amount = $('input[name="amount"]').val();
      console.log("Upvote initiated=");
      var comment = "upvote";
      $.ajax({
          type:'POST',
          url:"{% url 'upvote' pk=marking.id %}",
          data:{
              comment : comment,
              csrfmiddlewaretoken: '{{ csrf_token }}',
              action: 'post'
          },
          success: function(xhr, errmsg, err){
            window.location = "brand"
          },
          error : function(xhr,errmsg,err) {
          $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
              " <a href='#' class='close'>&times;</a></div>");
          console.log(xhr.status + ": " + xhr.responseText); 
      }
      });
  });
    </script>
   </div>
    <div class="modal fade bd-modal-lg-1" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
    
              <center><h4>Title</h4></center>
              <img class="img-fluid" src="{% static 'assets/img/about/about.png' %}">
              <br>
              <center><h4>Branding Video</h4></center>
    
              <div class="embed-responsive embed-responsive-16by9">
              <iframe class="rembed-responsive-item"  src="https://www.youtube.com/embed/UmljXZIypDc" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
              </div>
              <br>
              <button type="button" class="btn btn-secondary center" style="width: 200px;margin-left: auto;margin-right: auto;" data-dismiss="modal">Close</button>
    
    
              <br>
    
            </div>
          </div>
        </div>
        <div class="modal fade" id="bd-modal-lg-invest" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
          <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Event name - {{id.product_title}} </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
            </div>
          </div>
        </div>
    {% endfor %}
</div>
def upvote(request, pk):
    # getting the brand info
    event_data = MarketingMaestro.objects.get(pk = pk)
    # getting name of the particular id
    event_name = event_data.product_title
    print("Printing event name=", event_name)

    # upvote comment in the db
    if request.POST.get('action') == 'post':
        response_data = {}
        name = request.user.username
        emailID = request.user.email

        # getting user details
        response_data['name'] = name
        response_data['emailID'] = emailID
        comment = 'upvote'

        # creating the value
        BrandVotes.objects.create(
            name = name,
            emailID = emailID,
            product_title = event_name,
            comment = comment
         )
    return JsonResponse(
                {
                    'message': "success"
                }
    )

标签: pythondjango

解决方案


除了创建多个脚本之外,您可以只使用一个脚本,该脚本适用于DOM. 您只需要添加action="{% url 'upvote' pk=marking.id %}"到您的表单标签,这将为您提供路径和 id 以及您需要更新记录的位置。另外,使用class而不是 id 。然后,在您的 ajax 调用中使用$(this).attr("action")并使用 此操作值。url

演示代码

$(document).on('submit', '.post-invest', function(e) {
  e.preventDefault();
  var comment = "upvote";
  console.log($(this).attr("action"))
  $.ajax({
    type: 'POST',
    url: $(this).attr("action"), //pass here action
    data: {
      comment: comment,
      csrfmiddlewaretoken: '{{ csrf_token }}',
      action: 'post'
    },
    success: function(xhr, errmsg, err) {
      window.location = "brand"
    },
    error: function(xhr, errmsg, err) {
      $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: " + errmsg +
        " <a href='#' class='close'>&times;</a></div>");

    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="margin-left: 10px;margin-right: 10px;">

  <div class="card-columns">
    <div class="card ">
      <img class="card-img-top" src="" alt="Card image cap">
      <div class="card-body">
        <h5 class="card-title" name="title">mAbc</h5>
        <h5 class="card-title ids" name="title">1</h5>
        <p class="card-text">Random text</p>
        <br>

        <div class="row">
          <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-modal-lg-1">View more</button> &emsp;
          <a href="{% url 'invest' pk=marking.id %}" ;><button type="submit" class="btn btn-primary" data-toggle="modal" >Invest</button></a>
        </div>
        <br>
        <!--here add  action="{% url 'upvote' pk=marking.id %}"-->
        <!--also added class instead of id-->
        <form method="POST" action="{% url 'upvote' pk=1 %}" class="post-invest">
          <div class="row">
            <input class="btn btn-outline-secondary" id="upvote_button" type="submit" name="upvote" value="upvote">
          </div>
        </form>
      </div>
      <!--some other codes..-->
    </div>
    <div class="card ">
      <img class="card-img-top" src="" alt="Card image cap">
      <div class="card-body">
        <h5 class="card-title" name="title">XYZ</h5>
        <h5 class="card-title" name="title">2</h5>
        <p class="card-text">Random text</p>
        <br>

        <div class="row">
          <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-modal-lg-1">View more</button> &emsp;
          <a href="{% url 'invest' pk=marking.id %}" ;><button type="submit" class="btn btn-primary" data-toggle="modal" >Invest</button></a>
        </div>
        <br>
        <form method="POST" action="{% url 'upvote' pk=2 %}" class="post-invest">
          <div class="row">
            <input class="btn btn-outline-secondary" type="submit" name="upvote" value="upvote">
          </div>
        </form>
      </div>
    </div>
  </div>


推荐阅读