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:

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 = []


    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')
            added_record.date = request.POST.get('date')
            added_record.save()
            messages.success(request, "Record Added to Database Successfully!")
            return render(request,'allcountries.html')
        else:
            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 = '/'

urls.py

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'),
   
]

allcountries.html

{% extends '_base.html' %}


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


{% block content %}


<br>


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

<br>

{% 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"> -->
            </form>
            </div>
        </div>
        <br>
    </div>

</div>

{% endfor %}

{% endblock %}

myrecords.html

{% 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: {{record.country}}</h3>
          <div class="card-body">
            <p class="card-text">Date: {{record.date}} </p>
          </div>
          <button><a href="/record-delete/{{record.id}}">Delete</a></button>
          <br>
        </div>
        <br>
      </div>
    </div>
  </div>
{% endfor %}


{% endblock %}


deleterecord.html

{% extends '_base.html' %}

{% block page_title %} Delete {{record.country}} {% endblock %}

{% block content %}

<h4>Press Delete to complete</h4>

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

{% 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.

    @login_required
    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
            MyModel.objects.create(data=data)
                return HttpResponse('Data added to the database')
        else:
            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 = 
     $(this).attr('data-url');
     $.ajax({
         url: url,
         type: 'POST',
         data: {
             'data': 'your data here'
         },
         success: function(response) {
             console.log(response);
         },
         error: function(response) {
             console.log(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>
</form>

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(
                name=name,
                defaults={'description': description},
            )
        return HttpResponse('Data imported successfully')
    else:
        return render(request, 'import.html')

3)Add a URL pattern for the view function in your Django app's urls.py 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