[英]How do I get a variable value from javascript function to python function in django
I am trying to scan QR code using html,javascript as shown below by nurse_home.html.我正在尝试使用 html,javascript 扫描 QR 码,如下所示 nurse_home.html。 I am able to scan and see the content of the QR code on the website but I can't POST the QR code output represented by
我可以扫描并看到网站上二维码的内容,但我无法发布由 代表的二维码 output
<output type='POST' id='result' name='result' placeholder='qrCodeMessage'>
in nurse_home.html.在 nurse_home.html。 I want to post it to the python function: nurse_qrscan in views_nurse.py so that it can be written into the database Any help is greatly appreciated: The following are the relevant codes:
想发到python function: views_nurse.py中的nurse_qrscan 以便写入数据库 不胜感激: 以下是相关代码:
<nurse_home.html> <护士之家.html>
{% load static %}
{% block mainbody %}
<title>Django Online Barcode Reader</title>
<meta charset="utf-8">
{% csrf_token %}
<script src={% static "js/html5-qrcode.min.js" %}></script>
<style>
.result{
background-color: green;
color:#fff;
padding:20px;
}
.row{
display:flex;
}
</style>
{% csrf_token %}
<div class="row">
<div class="col">
<div style="width:500px;" id="reader"></div>
</div>
<div class="col" style="padding:30px;">
<h4>Scanned Result</h4>
<!--<div id="result" name="result">Result Here</div>-->
<output type="POST" id="result" name="result" placeholder="qrCodeMessage">
{% csrf_token %}
</div>
</div>
<script type="text/javascript">
function onScanSuccess(qrCodeMessage) {
document.getElementById('result').innerHTML = '<span class="result">'+qrCodeMessage+'</span>';
}
function onScanError(errorMessage) {
//handle scan error
}
var html5QrcodeScanner = new Html5QrcodeScanner(
"reader", { fps: 10, qrbox: 250 });
html5QrcodeScanner.render(onScanSuccess, onScanError);
</script>
{% endblock %}
Edited <script>
tag编辑的
<script>
标签
function getCookie(name) {
let cookie = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
return cookie ? cookie[2] : null;
}
function onScanSuccess(qrCodeMessage) {
document.getElementById("result").innerHTML = '<span class="result">' + qrCodeMessage + "</span>";
sendQrCode(qrCodeMessage);
}
async function sendQrCode(qrCode) {
const response = await fetch("/nurse_qrscan", {
method: "POST",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
},
body: JSON.stringify({
result: qrCode,
}),
})
.then((response) => response.json())
.then((data) => {
console.log(data)
axios.post(ToDJ("nurse_qrscan")) //**Newly added**
}
);
}
function onScanError(errorMessage) {
//handle scan error
}
var html5QrcodeScanner = new Html5QrcodeScanner("reader", {
fps: 10,
qrbox: 250,
});
html5QrcodeScanner.render(onScanSuccess, onScanError);
<views.py> <视图.py>
def nurse_home(request):
return render(request, 'nurse_home.html')
<views_nurse.py> <views_nurse.py>
@api_view(['GET',"POST"])
# Nurse scans QR
def nurse_qrscan(request):
### Test! nurse: QR
if request.method == 'POST':
print("Hi")
result = request.POST.get("result")
print(result)
# Saving the result to database, nurse_QR
# c = connection.cursor()
# c.execute("INSERT INTO nurse_QR (output) VALUES ('{0}');".format(result))
return Action.success()
<urls.py> <网址.py>
from hospital import view_nurse
from . import views
urlpatterns = [
# Main Page
path('', views.login, name='login'),
path('nurse/', views.nurse_home),
path('nurse_home/', views.nurse_home),
# Nurse
path('nurseLogin', view_nurse.nurseLogin, name='nurseLogin'),
path('nurse_qrscan', view_nurse.nurse_qrscan, name='nurse_qrscan'),
]
Actual database output (image 1)实际数据库output(图片1)
Expected database output (image 2): 36987-2480预期数据库 output(图片 2):36987-2480
Error obtained from print(result) - Image 3从打印(结果)中获得的错误 - 图 3
(Since "Hi" is printed, in "view_nurse.py", it shows that "
(由于打印了“Hi”,在“view_nurse.py”中,它显示“
if request.method == "POST"
如果 request.method == "POST"
is working.工作中。 However, "result" is not printed, showing that
但是,没有打印“结果”,表明
result = request.POST.get("result")
结果 = request.POST.get("结果")
is not working.)不管用。)
Do this in your <script>
tag:在您的
<script>
标签中执行此操作:
// Create a function to get the CSRF token
function getCookie(name) {
let cookie = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
return cookie ? cookie[2] : null;
}
function onScanSuccess(qrCodeMessage) {
document.getElementById("result").innerHTML =
'<span class="result">' + qrCodeMessage + "</span>";
// Call the function here
sendQrCode(qrCodeMessage);
}
async function sendQrCode(qrCode) {
const response = await fetch("/nurse_qrscan", {
method: "POST",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
},
body: JSON.stringify({
result: qrCode,
}),
})
.then((response) => response.json())
.then((data) => {
// Do your thing here.
});
}
function onScanError(errorMessage) {
//handle scan error
}
var html5QrcodeScanner = new Html5QrcodeScanner("reader", {
fps: 10,
qrbox: 250,
});
html5QrcodeScanner.render(onScanSuccess, onScanError);
Let me know which part troubles you for further explanation.让我知道哪一部分让您感到困扰,以便进一步解释。
Here is a breakdown.这是一个故障。
First, you get the CSRF token from your form with the following:首先,您使用以下代码从您的表单中获取 CSRF 令牌:
function getCookie(name) {
let cookie = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
return cookie ? cookie[2] : null;
}
Second, after generating the qrcode in the onScanSuccess
callback, you invoke sendQrCode
function with the qr code as argument:其次,在
onScanSuccess
回调中生成二维码后,以二维码作为参数调用sendQrCode
function :
function onScanSuccess(qrCodeMessage) {
document.getElementById("result").innerHTML =
'<span class="result">' + qrCodeMessage + "</span>";
// Call the function here
sendQrCode(qrCodeMessage);
}
Third, you use Fetch to send a POST request to nurse_qrscan
route:第三,您使用 Fetch 向
nurse_qrscan
路由发送 POST 请求:
async function sendQrCode(qrCode) {
const response = await fetch("/nurse_qrscan", {
method: "POST",
headers: {
// You pass the CSRF token generated from the function
"X-CSRFToken": getCookie("csrftoken"),
},
// Create an object with `result` as property
// and the `qrCode` as value.
// After that, convert it to JSON
body: JSON.stringify({
result: qrCode,
}),
})
....
It is a POST method because of method: "POST"
这是一个 POST 方法,因为
method: "POST"
Following that, you write functionality to handle the data returned from your Django view:之后,您编写功能来处理从 Django 视图返回的数据:
async function sendQrCode(qrCode) {
...
.then((response) => response.json())
.then((data) => {
// Do your thing here.
});
}
Edit :编辑:
Could you elaborate on how the data returned in ".then((data) => { // Do your thing here}" can be handled? I don't quite understand what needs to be written in there?
您能否详细说明如何处理“.then((data) => { // Do your thing here}”中返回的数据?我不太明白那里需要写什么?
In your nurse_qrscan
view, you are returning something:在您的
nurse_qrscan
视图中,您正在返回一些东西:
def nurse_qrscan(request):
...
return Action.success("Successful")
When it receives the POST request from fetch()
, it will return Action.success
.当它收到来自
fetch()
的 POST 请求时,它将返回Action.success
。 I can't tell if its JSON or you want to do something with the returned value to the frontend.我不知道它是 JSON 还是你想对前端的返回值做些什么。 If you want to access the value in Frontend using JavaScript.
如果要使用 JavaScript 访问前端中的值。
Assuming it is JSON, you can do this:假设它是 JSON,你可以这样做:
...
.then((response) => response.json())
.then((data) => {
console.log(data) // log the data returned from Django
});
}
In the line .then((response) => response.json())
, The value returned from the view(if JSON), it is parsed into native JavaScript.在
.then((response) => response.json())
行中,从视图返回的值(如果是 JSON)被解析为原生 JavaScript。
After the data is parsed, you can log it in the console or append in the DOM depending on your use case:解析数据后,您可以根据您的用例将其记录在控制台或 DOM 中的 append 中:
.then((data) => {
console.log(data) // log the data returned from Django
});
}
Second Edit :第二次编辑:
If I simply log the data returned from Django without adding "axios.post(ToDJ("nurse_qrscan")" to ".then((data) => {console.log(data)}, nothing gets written into the database
如果我只是记录从 Django 返回的数据,而不将“axios.post(ToDJ("nurse_qrscan")”添加到“.then((data) => {console.log(data)}”,则不会将任何内容写入数据库
Here is what am noticing.这是我注意到的。 You do not need
axios.post(ToDJ("nurse_qrscan")
, that's the point of the fetch
method in the solution. It sends the qrcode to Django.您不需要
axios.post(ToDJ("nurse_qrscan")
,这就是解决方案中fetch
方法的要点。它将二维码发送到 Django。
The right steps you can take is to verify that the value fetch is sending is the correct one:您可以采取的正确步骤是验证所发送的值提取是否正确:
...
const response = await fetch("/nurse_qrscan", {
...
body: JSON.stringify({
result: qrCode, // verify qrCode contains the expected value
}),
...
Perhaps, log the value in the console:也许,在控制台中记录值:
async function sendQrCode(qrCode) {
console.log(qrCode)
...
If the value is the correct one.如果值是正确的。 Let's proceed to debug the view.
让我们继续调试视图。
In the Django view, verify that you are receiving the expected value.在 Django 视图中,确认您收到的是预期值。 You can log the value in the terminal:
您可以在终端中记录该值:
def nurse_qrscan(request):
### Test! nurse: QR
if request.method == 'POST':
result = request.POST.get("result")
print(result) // verify the expected value is received.
If the above steps check out, then Django is receiving the correct qrcode but something is wrong with the query.如果上述步骤检查出来,那么 Django 收到了正确的二维码,但查询有问题。 And you also don't need the
axios.post
.而且您也不需要
axios.post
。
Now, I only used Django ORM. I am not sure if the query is correct.现在,我只用了Django ORM。我不确定查询是否正确。 So if the data isn't being saved, then the problem is the query or SQL.
因此,如果未保存数据,则问题出在查询或 SQL 上。
c.execute("INSERT INTO nurse_QR (output) VALUES ('{0}');".format(result))
I would suggest you make sure that the correct value is being sent through the Fetch() method.我建议您确保通过 Fetch() 方法发送正确的值。
By the way, what does ToDJ("nurse_qrscan")
in the Axios method do?对了,Axios方法中的
ToDJ("nurse_qrscan")
是干什么用的? does it get the qrcode and send it?它会获取二维码并发送吗? if so, maybe update the fetch body to that.
如果是这样,也许将获取主体更新为那个。 In my solution, I passed the qrcode in the
sendQrCode(qrCode)
function. As mentioned, verify that the correct qrcode is sent.在我的解决方案中,我在
sendQrCode(qrCode)
function 中传递了二维码。如上所述,验证是否发送了正确的二维码。
Fourth Edit : I just realized my solution lacked the functionality to parse the JSON data in the view.第四次编辑:我刚刚意识到我的解决方案缺少在视图中解析 JSON 数据的功能。
# import json at the top of the file
import json
def nurse_qrscan(request):
### Test! nurse: QR
if request.method == 'POST':
# parse the JSON data
data = json.load(request)
result = data.get('result')
print(result)
# Saving the result to database, nurse_QR
# c = connection.cursor()
# c.execute("INSERT INTO nurse_QR (output) VALUES ('{0}');".format(result))
return Action.success()
I have updated it and am confident it should work.我已经更新了它并且相信它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.