skip to Main Content

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


  1. 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 issue

    Login or Signup to reply.
  2. modify your error handler to only accept the data argument and log it to the console.

    the error is in the js function

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
  5. from rest_framework.response import Response
    
    def get(self, response):
        data = self.get_queryset()
        # assuming data is a dict object
        return Response(data)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search