如何在Django中使用JSON从数据库获取项目的ID时,应该如何提取项目的ID。

huangapple go评论64阅读模式
英文:

How to fetch the id of an item in Django when using JSON to fetch from the database

问题

以下是代码的翻译部分:

我有一个Django模板我正在在首页循环遍历多个项目当单击一个项目时应该显示一个模态框我通过导入它来包含它并显示与单击的项目相关的数据我正在使用JSONResponse来预填充模态框一旦模态框显示我想创建一个结账会话需要引用模态框中的项目的ID我卡在如何获取ID上
以下是用于显示模态框和预填充它的脚本

    let modal = document.getElementById("modal");
    modal.style.display = "none";

    function modalHandler(val, content_id) {
      if (val) {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (this.readyState == 4 && this.status == 200) {
            let data = JSON.parse(this.responseText);
            document.getElementById("subtotal").innerHTML = data.subtotal;
            document.getElementById("taxes").innerHTML = data.taxes;
            document.getElementById("website_fee").innerHTML = data.website_fee;
            document.getElementById("total").innerHTML = data.total;

            fadeIn(modal);
          }
        };
        xhr.open("GET", "/modal-content/" + content_id + "/", true);
        xhr.send();
      } else {
        fadeOut(modal);
      }
    }

以下是返回JSON数据的views.py

    def modal_content_view(request, content_id):
        my_model = get_object_or_404(MyModels, content_id=content_id)
        print("the model is {my_model.username}")
        data = {
            'subtotal': my_model.username,
            'taxes': '2.60',
            'website_fee': '0.87',
            'total': '23.47',
            'content_id': my_model.content_id
        }
        return JsonResponse(data)

以下是在单击结账按钮时获取数据的脚本

    <script type="text/javascript">
            var checkoutButton = document.getElementById('checkout-button');
           
            checkoutButton.addEventListener('click', function() {
            fetch("{% url 'checkout' content_id %}", {
            method: 'POST',
            data: JSON.stringify({
                  amount: "{{ cost }}" * 100,
                  description: "{{ title }}",
                  gig_id: "{{ gig_id }}",
                }),
            })
            .then(function(response) {
            return response.json();
            })
            .then(function(session) {
            return stripe.redirectToCheckout({ sessionId: session.id });
            })
            .then(function(result) {
            if (result.error) {
            alert(result.error.message);
            }
            })
            .catch(function(error) {
            console.error('Error:', error);
            });
            });
            </script>

以下是处理从上面脚本传递的content_id的视图

    @csrf_exempt
    def create_checkout_session(request, content_id):
        model = MyModels.objects.get(content_id=content_id)
        subscription = Subscription(model=model, is_subscribed=False, user=request.user)
    
触发模态框显示的onclick函数如下

    onclick="modalHandler(true, '{{content.model.content_id}}')"

我的问题是如何将'content_id'从模态框传递给处理结账的脚本

<details>
<summary>英文:</summary>

I have a Django template whereby I am looping through several items in the homepage. When an item is clicked, a modal which I have included by importing it should be shown and data related to the clicked item displayed. I am using JSONResponse to prepopulate the modal. Once the modal is shown, I want to create a checkout session which will require the id of the item being referred to in the modal. I am stuck at how to get the id.
Here is the script for showing the modal and prepopulating it:

    let modal = document.getElementById(&quot;modal&quot;);
    modal.style.display = &quot;none&quot;;
    
    function modalHandler(val, content_id) {
      if (val) {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (this.readyState == 4 &amp;&amp; this.status == 200) {
            let data = JSON.parse(this.responseText);
            document.getElementById(&quot;subtotal&quot;).innerHTML = data.subtotal;
            document.getElementById(&quot;taxes&quot;).innerHTML = data.taxes;
            document.getElementById(&quot;website_fee&quot;).innerHTML = data.website_fee;
            document.getElementById(&quot;total&quot;).innerHTML = data.total;
    
            fadeIn(modal);
          }
        };
        xhr.open(&quot;GET&quot;, &quot;/modal-content/&quot; + content_id + &quot;/&quot;, true);
        xhr.send();
      } else {
        fadeOut(modal);
      }
    }

Here is the views.py which returns the JSON data:

    def modal_content_view(request, content_id):
        my_model = get_object_or_404(MyModels, content_id=content_id)
        print(f&quot;the model is {my_model.username}&quot;)
        data = {
            &#39;subtotal&#39;: my_model.username,
            &#39;taxes&#39;: &#39;2.60&#39;,
            &#39;website_fee&#39;: &#39;0.87&#39;,
            &#39;total&#39;: &#39;23.47&#39;,
            &#39;content_id&#39;:my_model.content_id
        }
        return JsonResponse(data)

Here is the script that is supposed to fetch the data when the checkout button is clicked:

    &lt;script type=&quot;text/javascript&quot;&gt;
            var checkoutButton = document.getElementById(&#39;checkout-button&#39;);
           
            checkoutButton.addEventListener(&#39;click&#39;, function() {
            fetch(&quot;{% url &#39;checkout&#39; content_id %}&quot;, {
            method: &#39;POST&#39;,
            data: JSON.stringify({
                  amount: &quot;{{ cost }}&quot; * 100,
                  description: &quot;{{ title }}&quot;,
                  gig_id: &quot;{{ gig_id }}&quot;,
                }),
            })
            .then(function(response) {
            return response.json();
            })
            .then(function(session) {
            return stripe.redirectToCheckout({ sessionId: session.id });
            })
            .then(function(result) {
            if (result.error) {
            alert(result.error.message);
            }
            })
            .catch(function(error) {
            console.error(&#39;Error:&#39;, error);
            });
            });
            &lt;/script&gt;
Here is the view that handles the content_id passed from the script above:

    @csrf_exempt
    def create_checkout_session(request, content_id):
        model = MyModels.objects.get(content_id=content_id)
        subscription = Subscription(model=model, is_subscribed=False, user=request.user)
And here is the onclick function that triggers the modal to show:

    onclick=&quot;modalHandler(true, &#39;{{content.model.content_id}}&#39;)&quot;

My question is how do I pass the &#39;content_id&#39; from the modal to the script that handles checkout

</details>


# 答案1
**得分**: 0

Here is the translated code part without the content you mentioned:

```javascript
checkoutButton.addEventListener('click', function() {
    console.log("Button clicked");
    fetch("{% url 'checkout' model.content_id %}", {
        method: 'POST',
        data: JSON.stringify({
            amount: "{{ cost }}" * 100,
            description: "{{ title }}",
            gig_id: "{{ gig_id }}",
        }),
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(session) {
        return stripe.redirectToCheckout({ sessionId: session.id });
    })
    .then(function(result) {
        if (result.error) {
            alert(result.error.message);
        }
    })
    .catch(function(error) {
        console.error('Error:', error);
    });
});
英文:

Although it is not working as I wanted, I found a temporary solution to this. I soled the issue by placing the javascript inside the for loop where I want to get the content_id of the item. Here is how the script not looks

checkoutButton.addEventListener(&#39;click&#39;, function() {
console.log(&quot;Button clicked&quot;)
fetch(&quot;{% url &#39;checkout&#39; model.content_id %}&quot;, {
method: &#39;POST&#39;,
data: JSON.stringify({
amount: &quot;{{ cost }}&quot; * 100,
description: &quot;{{ title }}&quot;,
gig_id: &quot;{{ gig_id }}&quot;,
}),
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error(&#39;Error:&#39;, error);
});
});

huangapple
  • 本文由 发表于 2023年4月11日 02:58:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定