英文:
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("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);
}
}
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"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)
Here is the script that is supposed to fetch the data when the checkout button is clicked:
<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>
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="modalHandler(true, '{{content.model.content_id}}')"
My question is how do I pass the 'content_id' 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('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);
});
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论