I finally figured it out. I have divided process into multiple parts. I then make AJAX call to access it.
My urls.py
file:
from django.conf.urls import url
from .views import tag, check_tagid, scan_tag
urlpatterns = [
url(r'^tag/', tag, name="tag"),
url(r'^check_tagid/', check_tagid, name="check_tagid"),
url(r'^scan_tag/', scan_tag, name="scan_tag"),
]
My views.py
file:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import Student
import serial
def check_tagid(request):
"""Check if scanned tag id is already associated or not"""
tagid = request.GET.get('tagid', None)
if Student.objects.filter(tag_id__iexact=tagid).exists():
data = {
'is_taken': Student.objects.filter(tag_id__iexact=tagid).exists(),
'student': Student.objects.get(tag_id=tagid).name
}
else:
data = {
'is_taken': Student.objects.filter(tag_id__iexact=tagid).exists(),
}
return JsonResponse(data)
def scan_tag(request):
"""Function to check if tag is scanned or not"""
if request.is_ajax():
## Init RFID reader
data = serial.Serial(
port='/dev/ttyUSB1',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
context = {'tagid': data.read(12).decode("utf-8")}
return JsonResponse(context)
else:
return HttpResponse("This route only handles AJAX requests")
def tag(request):
return render(request, 'students/tag.html', {})
my tag.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<center><h1><div id="tag_id">Scanning for tag</div></h1></center>
<div id="if_exists"></div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get("/scan_tag/", function(data) {
console.log(data.tagid);
var x = document.createElement("INPUT");
x.setAttribute("id", "tag_id_in");
x.setAttribute("type", "hidden");
x.setAttribute("value", data.tagid);
document.body.appendChild(x);
// check tag
tagid = $("#tag_id_in").val();
console.log(tagid);
$.ajax({
type: "GET",
url: "{% url 'check_tagid' %}",
data: {
'tagid': tagid
},
success: function(data) {
if (data.is_taken) {
document.getElementById('tag_id').innerHTML = "Welcome "+data.student;
} else {
document.getElementById('tag_id').innerHTML = "No student with this tag id found";
}
}
});
});
});
</script>
</body>
</html>
All of this is now working as expected.
So, /tag/
is the main entry point. Now in tag.html
I use jQuery get
method on /scan_tag/
. It will return RFID tag number. Then I call AJAX on /check_tagid/
and it will true/false depending on whether the student is in the database or not.