如何使用JS和 AJAX 通过点击按钮向Django的数据库添加数据

vsmadaxz  于 2022-12-24  发布在  Go
关注(0)|答案(1)|浏览(121)

当我单击“Add to my records”按钮时,我尝试将呈现在页面上的数据从API端点添加到数据库中,如下图所示,我只尝试将“Date and Country”存储到数据库中(我的模型表只有date和country)enter image description here
我看过很多关于JS和 AJAX 在这种情况下是如何有用的资源,但是我对它的逻辑感到困惑。有没有人能解释一下应该如何做呢?
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 %}
wbgh16ku

wbgh16ku1#

您可以使用下面的 AJAX 片段在后端发送数据:

<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>

相关问题