How to add data from an API to Django's database when i click on a button

My question is going to be split into two halves for a better understanding. First half: I'm trying to add a bunch of data that I rendered on a page from an API endpoint, to my database when I click "Add to my records", as can be seen in the image below, keeping in my mind that there are a lot more cards such as for other countries and I'm only trying to store "Date and Country" into the database: enter image description here

and the second half, is after adding to the database I want to render them on another page, and if the database is empty aka the user hasn't added any data to the database yet, i want the page to show "now data to display" but if the user did, i want to render what's in the database.

enter image description here

Here's what I've tried so far:

from django.db import models

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

    def __str__(self):

def all_countries(request):
    first_response = requests.get('').json()
    results =  len(first_response['Countries'])
    my_new_list = []

    for i in range(0, results):

    # print(my_new_list)
    if request.method == "POST":
        if request.POST.get('country') and request.POST.get('date'):
            added_record = CountryData()
   = request.POST.get('country')
   = request.POST.get('date')
            messages.success(request, "Record Added to Database Successfully!")
            return render(request,'allcountries.html')
            return render(request,'allcountries.html')

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

class MyRecords(ListView):
    template_name = 'myrecords.html'
    model = CountryData
    context_object_name = "records_list"

class DeleteMyRecord(DeleteView):
    template_name = "deleterecord.html"
    model = CountryData
    success_url = '/'

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

urlpatterns = [
    path('', home, name='home'),
    path('allcountries', all_countries, name='all_countries'),
    path('myrecords', MyRecords.as_view(), name='my_records'),
    path('record-delete/<int:pk>', DeleteMyRecord.as_view(), name='record_delete'),


{% 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="{% url 'all_countries' %}">
                    {% csrf_token %}
                <h5 name = "country" class="card-header">Country: {{object.Country}}</h5>
                <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 type = "submit" class = "btn-danger btn-sm">ADD TO MY RECORDS </button>
                <!-- <input type="submit" name="" id="" value="ADD TO MY RECORDS"> -->


{% endfor %}

{% endblock %}


{% extends '_base.html' %}

{% block page_title %} My Records {% endblock %}

{% block content %}

{% for record in records_list %}

<div class="container">
    <div class="row">
      <div class="col-md-4">
        <div class="card text-dark" style="width: 30rem;">
          <h3 class="card-header">Country: {{}}</h3>
          <div class="card-body">
            <p class="card-text">Date: {{}} </p>
          <button><a href="/record-delete/{{}}">Delete</a></button>
{% endfor %}

{% endblock %}


{% extends '_base.html' %}

{% block page_title %} Delete {{}} {% endblock %}

{% block content %}

<h4>Press Delete to complete</h4>

    <form class='well form-horizontal' action="" method="POST">
            {% csrf_token %}
            <div class="form-group">
            <input type="submit" class="delete-button" value="Delete!">

{% endblock %}

To add data from an API to Django's database when you click on a button, you can use JavaScript to send an AJAX request to your Django server when the button is clicked. Here's an example of how you can do this:

  1. First, create a Django view function that will handle the request to add data to the database. This view should check for the request method and make sure it is a POST request. It should also authenticate the request and ensure that the user has the necessary permissions to add data to the database.

    def add_data(request):
        if request.method == 'POST':
            # Get the data from the API
            data = request.POST.get('data')
            # Add the data to the database
                return HttpResponse('Data added to the database')
            return HttpResponseBadRequest('Bad request')
  2. Next, create a button in your HTML template that will send the AJAX request when it is clicked. You can use the data-url attribute to specify the URL of the Django view that will handle the request.

    <button id="add-button" data-url="{% url 'add_data' %}">Add Data</button>
  3. Finally, use JavaScript to send the AJAX request when the button is clicked. You can use the jQuery $.ajax function to do this.

     $(document).ready(function() {
     $('#add-button').click(function() {
         var url = 
         url: url,
         type: 'POST',
         data: {
             'data': 'your data here'
         success: function(response) {
         error: function(response) {

This is just an example of how you can add data from an API to Django's database when you click on a button. You may need to modify this code to fit your specific needs.

I hope this help!

To add data from an API to Django's database when you click on a button in Django, you can follow these steps and it should work:

1)Create a form in your Django template that includes a button for submitting the form. The form should also include any other fields you need, such as an input field for the API URL.

<form method="post" action="{% url 'import_data' %}">
  {% csrf_token %}
  <label>API URL: <input type="text" name="api_url"></label>
  <button type="submit">Import data</button>

2)Write a view function to handle the form submission and import the data from the API. The view should fetch the data from the API, parse it into a suitable format for your Django model, and use the Django ORM (Object-Relational Mapper) to create or update the model instances with the fetched data.

import requests

from django.shortcuts import render
from django.http import HttpResponse

def import_data(request):
    if request.method == 'POST':
        # Read the API URL from the request
        api_url = request.POST['api_url']

        # Fetch the data from the API
        response = requests.get(api_url)
        data = response.json()

        # Iterate over the data and create or update the model instances
        for item_data in data:
            # Extract the fields we want to save
            name = item_data['name']
            description = item_data['description']

            # Check if the item already exists in the database
            item, created = Item.objects.update_or_create(
                defaults={'description': description},
        return HttpResponse('Data imported successfully')
        return render(request, 'import.html')

3)Add a URL pattern for the view function in your Django app's file.

from django.urls import path
from . import views

urlpatterns = [
    path('import/', views.import_data, name='import_data'),

Now, when you submit the form, the data from the API will be fetched and saved to the Django database.

Back to Top