📡

Using AJAX with Django Fetch API

Jun 7, 2024

Using AJAX with Django via Fetch API

Overview

  • Series focus: Using various tools for integrating AJAX with Python projects.
  • This specific lesson: Sending basic AJAX asynchronous GET and POST requests from a browser using the Fetch API to a Django application.

GET Request via Fetch API

  1. Triggering Action: Button Click

    • On clicking the green button, browser sends GET request to Django app.
    • Django app responds with a random number (1 to 10).
    • No page reload required.
  2. Django Project Structure

    • Basic project with one app (digits) and one URL pattern.
    • URL pattern handles requests to the root address via AjaxHandler class.
    • Class renders index.html on GET request.
  3. HTML Structure

    • index.html template includes:
      • Green button
      • Two empty unordered lists (left and right)
      • Bootstrap and a custom CSS file for styles
  4. JavaScript (main.js)

    • Added to the bottom of index.html before the closing body tag.
    • Listener on button click triggers getNumber function.
    • getNumber function sends GET request to Django app.
    • Uses Fetch API with await keyword for asynchronous call.
    • Response converted to JSON and logged to console.
  5. Django Backend

    • Imports randint from random module for generating random number.
    • AjaxHandler renders or responds with JSON based on request type.
    • Checks if request is AJAX by looking for X-Requested-With header.
    • Returns JSON response with random number for AJAX requests.
  6. Appending Number to List

    • In main.js, appends received number to left unordered list.
    • Uses getElementById to reference list and appendChild to add list item.

POST Request via Fetch API

  1. Triggering Action: Card Click

    • Clicking on a list item (card) sends a POST request to Django app.
    • Django responds with the float version of the sent number.
    • Updated card value rendered in the right unordered list.
  2. JavaScript Changes

    • Created makeRequest function to handle requests.
    • Function parameters: URL, method, body.
    • Added functionality to send POST request with body containing number.
    • Included CSRF token obtained from template to secure request.
    • On response, appends float value to the right unordered list.
    • Added event listener to left list items for handling card clicks.
  3. Django Backend Changes

    • Added post method to handle POST requests in AjaxHandler class.
    • Parses request body, deserializes JSON to Python dict.
    • Converts received number to float and returns as JSON response.

Testing and Final Remarks

  • Verified both GET and POST request functionalities: numbers correctly appended to respective lists.
  • Encouraged viewers to like, subscribe, and follow on social media.