I have a token and need to pass it to an API (created in views.py) in order to get back a time that’s generated. I have used Simple-JWT for token generation but I am not able to send it to the URL specified. See my code below:
models.py:
class My_time(models.Model):
id= models.ForeignKey(User, on_delete = models.CASCADE)
time = models.DateTimeField()
views.py:
#API to get back time (if existing) or create a new time and send it back to the HTML page via AJAX.
class TimeAPI(generics.ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = MySerializer
def get_queryset(self, request):
current_time = timezone.now()
if (My_time.objects.filter(time=current_time) in (None, '')):
time = My_time.objects.create(time=current_time) #saves it to my database
else:
pass
data = My_time.objects.values_list('time', flat=True)
return data #should return the data to the HTML page
serializers.py:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = My_time
fields = ('time')
urls.py:
urlpatterns = [
# ...,
path('time_api/',TimeAPI.as_view(), name = 'time_api'),
]
interface.html:
{% block content %}
<form method="POST">
<button type="button" class="btn btn-outline-info" id ='get_time'> Punch In </button>
<h4 id='display_time'></h4>
</form>
{% endblock content%}
JS code (within the HTML page):
{% block javascript %}
<script type="text/javascript">
$('#get_time').click(function () {
var access_token = localStorage.getItem('access'); #stored the token before in localStorage
$.ajax({
cache: false,
url: {% url 'time_api' %},
method: 'GET',
// datatype: 'json',
headers: { "Authorization": 'Bearer ' + access_token }
success: function(data) {
console.log(headers);
document.getElementById("display_time").innerHTML(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("No data");
}
});
});
</script>
{% endblock javascript %}
After clicking the button within my HTML page, I am not getting back the time generated. In fact, nothing happens.
This is the error within JS console:
Uncaught SyntaxError: Unexpected identifier
and it points to the success function in AJAX:
headers: { "Authorization": 'Bearer ' + access_token }
success: function(data) {
console.log(headers);
..... //remaining code
Can someone please explain what’s wrong? Thank you
5
Answers
try using the browser developer tools and check the js console output and include that here and also try to override the get method of your CBV and check for
if self.request.is_ajax
and return the data you need. that could be the issuemodify your error handler to only accept the
data
argument and log it to the console.the error is in the js function
define a new method
def get(self,request): queryset=self.get_queryset()# construct your html response and construct a json response and returñ that
then in js access the data value withdata.value
define a new method
def get(self,request): queryset=self.get_queryset()# construct your html response and construct a json response and returñ that
then in js access the data value with `data.value