How to add data to Django's database by the click of a button using JS and AJAX

I'm trying to add data that I rendered on a page from an API endpoint, to my database when I click "Add to my records" button, as can be seen in the image below, and I'm only trying to store "Date and Country" into the database (my model table has only date and country) enter image description here

I've seen many resources talking about how JS and AJAX are useful in this case but I'm lost with logic of it all. Is there any way someone could explain how it's supposed to be done.

models.py

from django.db import models

class CountryData(models.Model):
    country = models.CharField(max_length=100)
    date = models.DateTimeField()

    def __str__(self):
        return self.country

views.py

def all_countries(request):
    first_response = requests.get("https://api.covid19api.com/summary").json()
    results = len(first_response["Countries"])
    my_new_list = []
    data_list = []

    for i in range(0, results):
        my_new_list.append(first_response["Countries"][i])

    # print(my_new_list)

    if request.method == "POST":
        if request.POST.get("country") and request.POST.get("date"):
            added_record = CountryData()
            added_record.country = request.POST.get("country")
            # 2022-12-19T08:53:48.179Z
            added_record.date = datetime.datetime.strptime(
                request.POST.get("date"), "%Y-%m-%dT%I:%M:%S.%fZ"
            )
            added_record.save()
            return render(request, "allcountries.html")
        else:
            return render(request, "allcountries.html", )

    context = {"my_new_list": my_new_list}
    return render(request, "allcountries.html", context)

urls.py

from django.urls import path, include
from .views import home, all_countries

urlpatterns = [
    path("", home, name="home"),
    path("allcountries", all_countries, name="all_countries")
]

allcountries.html

{% extends '_base.html' %}


{% block page_title %} Covid19 Statistics For All Countries {% endblock %}


{% block content %}


<h3 class="text-center">Covid19 Statistics For All Countries </h3>

{% for object in my_new_list %}


<div class="row justify-content-center">
    <div class="col-sm-10 d-flex justify-content-center">
        <div class="card text-dark text-center" style="width: 20rem;">
            <div class="card-block card-body">
                <form method="POST" action="">
                    {% csrf_token %}
                    <h5 class="card-header" name="country">Country: {{object.Country}}, {{object.CountryCode}}</h5>
                    <br>
                    <p class="card-text">Total Confirmed Cases: {{object.TotalConfirmed}} </p>
                    <p class="card-text">Total Deaths Cases: {{object.TotalDeaths}} </p>
                    <p class="card-text">Total Recovered Cases: {{object.TotalRecovered}} </p>
                    <p class="card-text" name="date">Date: {{object.Date}}</p>
                    <button class="btn btn-success" type="submit">ADD TO MY RECORDS </button>
                </form>
            </div>
        </div>
        <br>
    </div>
</div>

{% endfor %}

{% endblock %}

You can use the following ajax snippet to send data in the backend:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
  $.ajax({
        type: 'POST',
        url: 'url', #leave blank if URL is same as the current one
        data: {
            'country': 'county_name',
            'date': 'date_value', 
        },
        success: function(response) {
            # depending upon the response from the server you can make an alert here.
        },
        error: function(response){
          # If some error occurred on the backend you can show error message from here
       }

    });

</script>
Back to Top