【问题标题】:How to pass on value to particular title in django如何将价值传递给 django 中的特定标题
【发布时间】:2021-06-18 10:48:05
【问题描述】:
  • 我已从表 MarketingMaestro 中获取值,其结构如下所示 Structure of MarketingMaestro
class MarketingMaestro (models.Model):
    product_title = models.CharField(max_length=250)
    total_value = models.IntegerField()
    total_votes = models.IntegerField()
  • 我能够完美地使用 for 循环获取值,该循环在 HTML 中提供以下输出 [![在此处输入图片说明][1]][1]
  • 因此,当您点击其中一张卡片上的Invest 按钮时,您将能够为该特定项目投资一些金额。
  • 弹出窗口看起来像这样 [![在此处输入图片说明][2]][2]
  • 所以我在这里面临两个问题,我无法显示单击其投资按钮的特定项目名称,添加金额并提交后我没有收到任何错误,但它没有保存在数据库中.
  • 我不知道应该如何将项目名称传递给 ajax 代码。
  • AJAX code
  $(document).on('submit', '#post-form',function(e){
      // console.log("Amount="+$('input[name="amount"]').val());
      e.preventDefault();
      // getting the value entered
      amount = $('input[name="amount"]').val();
      console.log("Amount entered by user="+amount);
      $.ajax({
          type:'POST',
          url:'{% url "brand" %}',
          data:{
              name: name,
              emailID: emailID,
              product_title: product_title,
              total_investment : total_investment,
              amount: amount,
              csrfmiddlewaretoken: '{{ csrf_token }}',
              action: 'post'
          },
          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); 
      }
      });
  });
  • HTML代码
<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>
        <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;
        <button onclick="invest({{id}})" type="button" class="btn btn-primary" data-toggle="modal" data-target="#bd-modal-lg-invest">Invest</button>
        &emsp;
      </div>
      <br>
        <label>Total Vote
          <input type="text" id="number" readonly/>
          <br>
        </label>
        <label for="recipient-name" class="col-form-label">Total amount invested {{marking.total_value}}
        <label for="recipient-name" class="col-form-label">Total Votes {{marking.total_votes}}
      <form>
        {% csrf_token %}
        <div  class="row" >
          <button type="button" class="btn btn-outline-success" onclick="incrementValue()" name="uptvote"><i class="fa fa-arrow-up"></i>UPVOTE</button>
          &emsp;
          <button type="button" class="btn btn-outline-secondary" onclick="decrementValue()" name="downvote"><i class="fa fa-arrow-down"></i>DOWNVOTE</button>
        </div>
      </div>
    </form>
    </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 class="modal-body">
                
                <div class="form-group">      
                    <label for="recipient-name" class="col-form-label">Project name {{marking.product_title}}   
                    <br>                                              
                    <label for="recipient-name" class="col-form-label">Invest amount out of {{context.remaining_amount}}<!-- number 100 should change dynamically after investment (ajax) -->:</label>
                    <form role="form" method="POST" id="post-form" enctype="multipart/form-data">
                      {% csrf_token %}
                      <input type="text" class="form-control" id="recipient-name" name="amount">
                  </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Submit</button> <!-- investment saved to database -->
              </div>
            </div>
          </div>
        </div>
    {% endfor %}

【问题讨论】:

  • 您可以像在 for 循环中访问它一样访问它
  • 您好,请显示html代码。
  • @Swati 我已经更新了问题中的HTML 代码。

标签: python django ajax


【解决方案1】:

实际上,为了了解您的问题,我需要查看更详细的源代码。但无论如何,我会尝试解决它。据我了解,您不会在 MarketingMaestro 对象中使用 id
首先,当您从MarketingMaestro 对象获取数据时,也发送 id (它是由 Django 自动创建的)。您的对象将如下所示:

[
   {
      id: 1,
      product_title: "title1",
      total_value: 300,
      total_votes: 20
   },
   {
      id: 2,
      product_title: "title2",
      total_value: 450,
      total_votes: 15
   }
] 

现在,您可以将 id 值传递给 invest 按钮的onclick 事件。

<button onclick="invest({{id}})">Invest</button>

您的 js 将如下所示:

function invest(id) {
   let clickedObject = myObjectList.filter(o => o == id); //came from django
   //now you're able to access all the fields of object clicked
}

最后,在 Django 中回答您的问题,我猜您忘记使用 save() 方法。可能正因为如此,它不会将其保存在数据库中。为了准确解决您的问题,请将您的源代码放在服务器端。

PS:id在Django中被命名为pk

【讨论】:

  • 但是如何访问弹出菜单中的值,如何将值传递给那个?
  • 这取决于您使用哪个弹出库。如果您的库接受一个对象作为参数,那么只需将clickedObject 传递给您的模态,如果没有,则为模态标记提供一个 id(例如:
    $('#modalTitle').text(clickedObject.product_title)
  • invest 方法之后附加确切的代码:$('#exampleModalLongTitle').text(clickedObject.product_title)。通过这种方式,您可以动态更新所有字段。
【解决方案2】:
  • 解决方案
  • 我刚刚创建了一个新页面,我将在其中将特定事件的 id 值传递给新页面
  • HTML 部分

    <a href="{% url 'invest' pk=marking.id %}";><button type="button" class="btn btn-primary" data-toggle="modal" >Invest</button></a>

  • urls.py

    path('invest/(?P<pk>\d+)/', views.invest, name='invest'),

  • views.py
    def invest(request, pk):
        event_data = MarketingMaestro.objects.get(pk = pk)
        context = {
                'product_title' : event_data.product_title
                }
        return render(request, 'invest.html', {'context' : context})

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签