Django REST Framework: Converting Data to JSON and Fetching it Using JavaScript from my API

How can I retrieve data from my API using JavaScript?

My objective is to present my model data in the form of charts or graphs. For the visualization part, I have chosen Charts.js. Currently, I am able to display a chart in my template with default data. Now, I want to send my model data to the template and integrate it into Chart.js. Chart.js requires data in JSON format, so I have set up an API with the Django REST Framework to get the output.

Folder Structure

  visual # -- my project
    ├── cars # -- API
    │   ├── templates
    │   │   └── cars   
    │   │       └── cars_home.html
    │   ├── <...>
    │   ├── urls.py
    │   ├── serializers.py
    │   └── views.py
    ├── charts
    ├── static
    │   ├── css
    │   ├── img
    │   └── js
    │       ├── chart_2.js
    │       └── <...>
    ├── templates
    │   ├── base
    │   │   └── base.html
    │   └── includes
    ├── visual
    │   ├── settings.py
    │   ├── urls.py
    │   └── views.py   *db.sqlite3
    └── manage.py

../ cars / urls.py

from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from cars import views
from cars.views import CarsHomeView

app_name = 'cars' 

urlpatterns = [
    path('carshome/', CarsHomeView.as_view(), name='cars_home'),
    path('cars/', views.SnippetList.as_view()),
    path('cars/<int:pk>/', views.SnippetDetail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

Here is the Output of my API

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "count": 4,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 3,
            "name": "Audi",
            "price": 11
        },
        {
            "id": 4,
            "name": "Audi",
            "price": 11
        },
        {
            "id": 2,
            "name": "Mercedes",
            "price": 22
        },
        {
            "id": 1,
            "name": "BMW",
            "price": 99
        }
    ]
}

How can I fetch the data from my API using JavaScript?

My approach is to first simply print the data in my template to verify that it works. I am also trying two different methods. One is to place the JavaScript code in an external file in my static/js folder, which worked with Chart.js and default values. However, I am also including the JS code in my template, as there may be issues with referencing my API from the static folder.

Here is the template.html. I have added the JS fetch code from a tutorial site, but unfortunately, I could not find a Django-JS example.

../ cars / templates / cars / cars_home.py

{% extends 'base.html' %}

{% load static %}

{% block content %}

<div class="container-fluid">
    <div class="row">
        <h1>Welcome to Cars Home</h1>
    </div>

    <div class="row">


        <!--via external js-->
        <script src="{% static 'js/chart_2.js' %}"></script>


        <!--via internal js-->
        <script>
            fetch('http://127.0.0.1:8000/cars/?format=json')
                .then(response => {
                    return response.json()
                })
                .then(data => {
                    // Work with JSON data here
                    console.log(data)
                })
                .catch(err => {
                    // Do something for an error here
                })

        </script>

    </div>
</div>

{% endblock content %}

Another question I have is, do I need all the additional information in my API output?

{"count":4,"next":null,"previous":null,"

I believe it would be neater if it looked like this?

"results":[{"id":3,"name":"Audi","price":11},{"id":4,"name":"Audi","price":11},{"id":2,"name":"Mercedes","price":22},{"id":1,"name":"BMW","price":99}]}

Update: It appears that my Firefox console was experiencing some issues and was not displaying the array and objects. Switching to the Chrome console resolved the problem and showed me everything.

Answer №1

There are a few key considerations to keep in mind.

"count":4,"next":null,"previous":null,"
is important for pagination of API resources in the future. This will help you control the number of items displayed per page and enable navigating through different pages on your website seamlessly. For example, if you display 10 items per page and have a total count of 25, you would show 3 potential pages, like with an online shopping site. It's best to plan for this in advance.

If your script isn't producing any results and you're not seeing any data in the console, make sure you can access the actual website in your browser. Keep in mind that I can't access your local machine.

<script>
            fetch('http://127.0.0.1:8000/cars/?format=json')
                .then(response => {
                    return response.json()
                })
                .then(data => {
                    // Apply operations to JSON data here
                    console.log(data)
                })
                .catch(err => {
                    // Handle errors here
                })

        </script>

Consider exploring Jinja, a middleware specifically designed for working with Django backends. It allows you to seamlessly integrate data into HTML templates, like so:

{% for car in cars %}
  <li> <strong>{{car.name}}:</strong> {{car.price}} <li>
{% endfor %} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eliminate Quotation Marks and Commas in String Data Using React

I created a code snippet to input data into a table and added a button function for downloading the entire table. However, when I open the downloaded file using notes or a text editor, it shows multiple double quotes and commas that I need to eliminate. He ...

Issues with Rails comments not displaying properly when using ajax requests

I've implemented ajax comments in my rails app and while I can see the comments are being processed in the console, they're not displaying/rendering on the page. My javascript appears to be functioning correctly, but I'm unsure where the iss ...

Tips for updating page content without needing to refresh the page

Have you noticed on Foursquare's website: They have new feeds appearing automatically without the need to refresh the page. I'm working on a backend system to display user specific feeds. How can I achieve the same effect as Foursquare? ...

JavaScript - Dynamic rotation algorithm

I recently developed a piece of code to manage object rotation in a THREE.js environment. Although the issue is not specific to 3D. My goal is to have my object (referred to as 'this') rotate by 0.25 radians each time a function is called, until ...

Guide on extracting JsonArray data and assigning it to a TextView in an Android application

Here is the JSON response I received when hitting a URL with the parsing parameter strlogid=101 [ { "earnpoints": 411, "type": "C" }, { "earnpoints": 1600, "type": "G" }, { "earnpoints": 13540, "type": "I" } ] B ...

Why is the jQuery datepicker malfunctioning when nested within ng-repeat in AngularJS?

I am currently facing an issue with the jquery ui date picker in my AngularJS application. The date picker is functioning correctly outside of any ng-repeat loops, but it stops working when placed within one. <input type="text" class="form-control date ...

The persistent redirection issue in Node.js - Middleware

Currently, I am in the process of developing a middleware using node js and express. The main objective of this middleware is to redirect users to a login page if they are not authenticated. Although the redirection to the login page works as intended, th ...

Activating list anchor upon click

I have a list that looks like this: <!-- List --> <ul class="nav nav-sm nav-tabs nav-vertical mb-4 steps-sampling"> <li class="nav-item"> <a class="nav-link active" id="link1" href="{{ ...

Transmitting form-like data via AJAX

My webpage has a feature that allows users to update their recipes. The page includes a simple form for users without javascript, and AJAX functionality for those with javascript enabled. When I submit the form, it perfectly binds to my MVC model and every ...

Should I refrain from storing user files on my server?

Greetings! I am currently working on an Express js + React js application and using MySQL for database management. I have successfully stored user information like email, hashed passwords, and user IDs in the database. However, now I want to create ...

Efficiently retrieving Django model relations through JSON

Struggling to properly title this question, but please bear with me as I explain my dilemma. I am in the process of creating an app for my hockey team that involves a django backend and a mobile app using JSON communication (via django-rest-framework). On ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

Troubleshooting: React Native and OneSignal notifications not showing up

Currently, I am developing an app in React Native and working on integrating notifications with OneSignal. Although I am able to efficiently receive notifications, I do not want them to be displayed on the screen when they are received. I came across a ` ...

What purpose does Can Order serve in Django Formsets?

After spending a considerable amount of time over the past day exploring the can order field within Django Formsets, I am still puzzled about its purpose. It seems that it does not update the database and only adds an order number field to the form. But be ...

Generate an image of a "button" with dynamic hover text

I am trying to create a clickable image with dynamically changing text overlaid on it. I have the PHP code that retrieves the necessary information for the text, but I am struggling to create the button as I am new to this type of task. Here is an example ...

Authorization in Confluence REST API

Currently, a user is logged in to Confluence; There is an external web application that saves attachments to a specific page. In order to make REST calls from the external app, I need the user's credentials for Confluence (which I do not have because ...

What is the best method to close a polygon infowindow when hovering over a map marker?

I am currently working on integrating Google Maps which includes a set of polygons representing state boundaries and markers representing cities within each polygon. I want to display information when hovering over a polygon/state. My question is: how can ...

Tips for creating a smooth scrolling header menu on a standard header

<script> $(document).ready(function(){ $(".nav-menu").click(function(e){ e.preventDefault(); id = $(this).data('id'); $('html, body').animate({ scrollTop: $("#"+id).o ...

Adjust the text area to automatically expand or shrink based on the text it contains

Is there a way to automatically adjust the size of a textarea based on its content? Here is the code I am currently using for this purpose: var element = document.getElementById(event.target.id); var content = $(this).val().trim(); if (content == "") { ...

Refining/searching with selectors in AJAX response

As someone who is new to javascript and coding in general, I am facing a challenge with filtering and manipulating data received through an AJAX request. Unfortunately, I do not have access to the server-side code. The server responds with rota information ...