[Python] How to fetch the response from my Django view & url and console.log the response in...

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I've been trying to console.log the Json(response) from my View in my home.html template with no success. Here is my code:

    Views.py

    def Tweets_view(request, *arg, **kwargs):
    qs = Tweets.objects.all()

    for x in qs:
    tweet_list = { 'id': x.id, 'content': x.content }
    context = { 'response': tweet_list }

    return JsonResponse(context)


    urls.py

    from django.contrib import admin
    from django.urls import path
    from tweets.views import Tweets_view_id, Tweets_view

    urlpatterns = [
    path('admin/', admin.site.urls),
    path('tweets', Tweets_view), #N.B This is the URL I'm trying to access.
    path('tweets/<int:tweet_id>', Tweets_view_id)
    ]



    home.html

    {% extends './base.html' %}

    {% block content% }
    <div id="tweets">
    LOADING ...
    </div>

    <script>

    const tweetsElement = document.getElementById("tweets")
    const xhr = new XMLHttpRequest()
    const method = "post"
    const url = "/tweets"
    const responseType = "json"

    xhr.responseType = responseType
    xhr.open(method, url)
    xhr.onload = function () {
    const serverResponse = xhr.response
    var listedItems = serverResponse.response
    console.log(listedItems)
    }

    xhr.send()

    </script>
    {% endblock content% }


    my browser (Displays nothing in the console)

    This is the link to the my browser display image. No data displays in my console.

    Continue reading...

Compartilhe esta Página