Ross
Ross

Reputation: 2417

Django How to add data to database from javascript

I am have created a page in django, on this page I have create a button that calls a JavaScript function which in turn gets data from a API. This part of my code works as expected as it writes the response data to the console. However I cannot seem to get that data to be inserted into the model I have created in django.

I am not sure how python/javascript/models are meant to all link together.

models.py

from django.db import models


class Set(models.Model):
    scry_id = models.CharField(max_length=255)
    code = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    set_type = models.CharField(max_length=255)
    release_date = models.DateField()
    card_count = models.IntegerField()
    block_code = models.CharField(max_length=255, null=True)
    block_name = models.CharField(max_length=255, null=True)
    parent_set_code = models.CharField(max_length=255, null=True)
    digital_only = models.BooleanField(default=False)
    foil_only = models.BooleanField(default=False)
    nonfoil_only = models.BooleanField(default=False)
    icon = models.CharField(max_length=255)
    status = models.BooleanField(default=False)

    def __str__(self):
        return self.name

sets.html

{% extends "main/index.html "%}

{% block content %}
  <div class="background card">
    <div class="card-body">
      <button class="btn" id="setRefresh" style="border: 1px solid" onclick="setRefresh()"><i class="fas fa-sync"></i></button>

    </div>
  </div>
{% endblock%}

custom.js

function setRefresh() {
  const Url="https://api.scryfall.com/sets";
  fetch(Url)
    .then(res => res.json())
    .then(data => obj = data.data)
    .then(() => obj.sort(function(a,b){return a.released_at.localeCompare(b.released_at);}))
    .then(() => {
      for (var i = 0; i < obj.length; i++) {
        //console.log(obj[i].name);
      }
    })
}

view.py

def sets(request):
    return render(request,
                  "main/sets.html",
                  {"Sets": Set.objects.all})

Upvotes: 1

Views: 2589

Answers (2)

iliya
iliya

Reputation: 531

There are two missing parts. First you need to have a url to listen for changes and then you need to have a view function where you want to set data. And you need to make some changes for the JS part of your code.Example below can clear this up and it is functional as well:

views.py:

def views_name(request):
    if not request.is_ajax():
        return HttpResponseBadRequest()
    try:
        if request.method == 'POST':
            post_id = request.POST.get('post')
            YourModel.objects.create(id=post_id)
    except Exception:   # pragma: no cover
        return HttpResponseBadRequest()

urls.py:

urlpatterns = [
    url(r'^whatever/$', views.views_name, name='whatever'),
]

custom.js:

$(function () {
    $(".class-name").click(function () {
        var csrf = $(this).attr('csrf');
        var post = $(this).attr('page-id');
        $.ajax({
            url: '/whatever/',
            data: {
                'post': post,
                'csrfmiddlewaretoken': csrf
                },
            type: 'post',
            cache: false,
            success: function (returned_values) {
                // do whatever you want after success!                
                },
        });
    });
})

Upvotes: 1

Ismael
Ismael

Reputation: 92

There are two ways to do it

  1. Method 1 : After retrieving the data, send them to your django app instead of logging them into the console . have a django view that handles the corresponding request coming from your js code containing the data then adding them to the db. In other words you should fetch again , but this time to your django app using a post request .

.Your view should look like this :

    from .models import Set
    from django.http import HttpResponse
    import json
    
    def save(request):
        data=json.loads(request.body)
        for entry in data:
            s = Set()
            s.scry_id=entry["scry_id"]
            #in the next lines you map entry fields to Set fields



            s.save()
         return HttpResponse("ok")
  1. Method 2 : Your button call your django app on click , then your django app retrieve the data from https://api.scryfall.com/sets itself then save them to the db. Your code should look like this

    from .models import Set
    from django.http import HttpResponse
    import json
    import requests
    
    def save(request):
        response = requests.request("GET", "https://api.scryfall.com/sets")
        data=response.json()
        for entry in data:
            s = Set()
            s.scry_id=entry["scry_id"]
            #in the next lines you map entry fields to Set fields
    
    
    
            s.save()
         return HttpResponse("ok")
    

Of course in either case don't forget to map your urlconf to the save view

Upvotes: 0

Related Questions