Automatically adding admin data to the front page

So I was trying to build a functionality that takes data from a modal form and then after adding it to the db the data is automatically added to the page without reload. Here’s what I have
the HTML

<div class="card mb-3">
                            <div class="card-body">
                                <div class="d-flex align-items-center mb-5">
                                    <h3>Address</h3>
                                </div>
                                <div class="mb-4">
                                    <div class="d-flex align-items-center mb-1"><span class="me-2 uil uil-estate"></span>
                                        <h5 class="mb-0">Address</h5>
                                    </div>
                                    <p id="address" class="mb-0 text-body-secondary">{{ cooperatives.address }}</p>
                                </div>
                                <div class="mb-4">
                                    <div class="d-flex align-items-center mb-1"><span class="me-2 uil uil-map"></span>
                                        <h5 class="mb-0">Constituency</h5>
                                    </div>
                                    <p id="constituencyOfOrigin" class="mb-0 text-body-secondary">{{ cooperatives.constituency_of_origin }}</p>
                                </div>
                                <div class="mb-4">
                                    <div class="d-flex align-items-center mb-1"><span class="me-2 uil uil-map"></span>
                                        <h5 class="mb-0">Ward</h5>
                                    </div>
                                    <p id="ward" class="mb-0 text-body-secondary">{{ cooperatives.ward }}</p>
                                </div>
                                <div class="mb-4">
                                    <div class="d-flex align-items-center mb-1"><span class="me-2 uil uil-map"></span>
                                        <h5 class="mb-0 text-body-highlight">County</h5>
                                    </div>
                                    <p id="countyOfOrigin" class="mb-0 text-body-secondary">{{ cooperatives.county_of_origin }}</p>
                                </div>
                                <div>
                                    <div class="d-flex align-items-center mb-1"><span class="me-2 uil uil-windsock"></span>
                                        <h5 class="mb-0 text-body-highlight">Country</h5>
                                    </div>
                                    <p id="countryOfOrigin" class="mb-0 text-body-secondary">{{ cooperatives.country_of_origin.name }}</p>
                                </div>
                            </div>
                        </div>

And the js

document.addEventListener("DOMContentLoaded", function () {
  // Function to handle account registration
  function registerAccount(event) {
    // Prevent page reload
    event.preventDefault();

    // Trigger button animation
    document.getElementById("submitButton").innerHTML = `
            <span id="loadingSpinner" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
            <span id="loadingText">Loading...</span>
        `;

    // Validate form inputs
    var cooperativeName = document.getElementById("cooperativeName").value;
    var cooperativeType = document.getElementById("cooperativeType").value;
    var cooperativeLogo = document.getElementById("cooperativeLogo").files[0];
    var country = document.getElementById("country").value;
    var countyName = document.getElementById("countyName").value;
    var constituencyName = document.getElementById("constituencyName").value;
    var agricultureType = document.getElementById("agricultureType").value;
    var cropsGrown = document.getElementById("cropsGrown").value;
    var ward = document.getElementById("ward").value;
    var cooperativeAddress =
      document.getElementById("cooperativeAddress").value;

    // Construct FormData object
    var formData = new FormData();
    formData.append("cooperativeName", cooperativeName);
    formData.append("cooperativeType", cooperativeType);
    formData.append("cooperativeLogo", cooperativeLogo);
    formData.append("country", country);
    formData.append("countyName", countyName);
    formData.append("constituencyName", constituencyName);
    formData.append("agricultureType", agricultureType);
    formData.append("cropsGrown", cropsGrown);
    formData.append("ward", ward);
    formData.append("cooperativeAddress", cooperativeAddress);

    // Send form data to server using fetch API
    fetch("/userprofile/register/", {
      method: "POST",
      body: formData,
      headers: {
        "X-CSRFToken": document.querySelector(
          'input[name="csrfmiddlewaretoken"]'
        ).value,
      },
    })
      .then((response) => response.json())
      .then((data) => {
        if (data.success) {
          // Assuming cooperativeExists is a boolean variable indicating whether a cooperative profile exists
          showAlert("success", data.message);

          // Update the cooperative name
          document.getElementById("cooperativeName").innerText =
            data.cooperative.cooperative_name;

          // Update other fields similarly
          document.getElementById("agriculturalType").innerText =
            data.cooperative.agricultural_type;
          document.getElementById("cooperativeType").innerText =
            data.cooperative.cooperative_type;
          document.getElementById("countryOfOrigin").innerText =
            data.cooperative.country_of_origin;
          document.getElementById("countyOfOrigin").innerText =
            data.cooperative.county_of_origin;
          document.getElementById("constituencyOfOrigin").innerText =
            data.cooperative.constituency_of_origin;
          document.getElementById("ward").innerText = data.cooperative.ward;
          document.getElementById("address").innerText =
            data.cooperative.address;
          document.getElementById("cooperativeName").innerText =
            data.cooperative.cooperative_name;
          // Update other profile details similarly
          document.getElementById("createdDate").innerText =
            data.cooperative.formatted_created_at;
          document.getElementById("membershipID").innerText =
            data.cooperative.membership_id;
        } else {
          showAlert("danger", data.message);
        }
        // Reset button animation
        document.getElementById("submitButton").innerHTML =
          '<span id="buttonContent">Register Profile</span>';
      })
      .catch((error) => {
        console.error("Error:", error);
        showAlert("danger", "An error occurred while processing your request");
        // Reset button animation
        document.getElementById("submitButton").innerHTML =
          '<span id="buttonContent">Register Profile</span>';
      });
  }

  // Function to dynamically show Bootstrap alerts
  function showAlert(type, message) {
    var alertDiv = document.createElement("div");
    alertDiv.classList.add(
      "alert",
      `alert-subtle-${type}`,
      "alert-dismissible",
      "fade",
      "show",
      "show-notification"
    );
    alertDiv.setAttribute("role", "alert");
    alertDiv.innerHTML = `
            <strong>${
              type.charAt(0).toUpperCase() + type.slice(1)
            }!</strong> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;
    document.getElementById("alertContainer").appendChild(alertDiv);
  }

  // Event listener for form submission
  document
    .getElementById("submitButton")
    .addEventListener("click", registerAccount);
});

The problem is that while the data is being added to the database, the page is not automatically loading the data without a reload which is what I wanted. Please help

What does your view look like that you’re posting the data to?

What is it returning?

Here is my views, first is the function that returns the html page

from django.shortcuts import render, redirect
from django.http import JsonResponse
from django_countries import countries as django_countries
from .models import *
from django.views.decorators.http import require_POST
from taggit.utils import parse_tags
from django.contrib.auth.decorators import login_required

@login_required(login_url='/authenticate/login')
def profileOverview(request):
    # Get the Cooperative instance associated with the current user
    cooperative_exists = Cooperative.objects.filter(user=request.user).exists()

    context = {
        "cooperative_types" : Cooperative.COOPERATIVE_TYPE_CHOICES,
        "countries" : django_countries,
        "agriculture_types" : Cooperative.AGRICULTURAL_TYPE_CHOICES,
        "cooperative_exists" : cooperative_exists,
    }
    return render(request, 'profile/index.html', context)

And then the function that adds the profile

@require_POST
def register_cooperative(request):
    try:
        # Retrieve data from the POST request
        cooperative_name = request.POST.get('cooperativeName')
        cooperative_type = request.POST.get('cooperativeType')
        cooperative_image = request.FILES.get('cooperativeLogo')
        country_of_origin = request.POST.get('country')
        county_of_origin = request.POST.get('countyName')
        constituency_of_origin = request.POST.get('constituencyName')
        agricultural_type = request.POST.get('agricultureType')
        crops_grown = request.POST.get('cropsGrown')
        crops_grown_tags = parse_tags(crops_grown)
        ward = request.POST.get('ward')
        cooperative_address = request.POST.get('cooperativeAddress')

        # Validate form inputs (optional)
        if not (cooperative_name and cooperative_type and country_of_origin and county_of_origin and constituency_of_origin and agricultural_type and crops_grown and ward and cooperative_address):
            return JsonResponse({'success': False, 'message': 'All fields are required'})

        # Save the data to the database
        cooperative = Cooperative(
            user=request.user,
            cooperative_name=cooperative_name,
            cooperative_image=cooperative_image,
            cooperative_type=cooperative_type,
            country_of_origin=country_of_origin,
            county_of_origin=county_of_origin,
            constituency_of_origin=constituency_of_origin,
            agricultural_type=agricultural_type,
            ward=ward,
            address=cooperative_address,
            # Add other fields as needed
        )
        cooperative.save()

        cooperative.crops_grown.add(*crops_grown_tags)

        # Return success message
        return JsonResponse({'success': True, 'message': 'Cooperative registered successfully'})
    except Exception as e:
        # Return error message
        return JsonResponse({'success': False, 'message': str(e)})```

Now, I’m not really familiar with the fetch API, so I can’t help much with the JavaScript, but I’d make the guess that what I’m reading is saying that you’re trying to update the page with data being returned by the view.

However, I don’t see anything in the view that is actually returning the data to the calling script.

There’s no key “cooperative” in that response dict.