1

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

2 Answers 2

1

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!                
                },
        });
    });
})
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

I have added the view in method two called setrefresh, however I am unsure what you mean by button call your django app and when I try to add path('sets', views.setrefresh(), name="setRefresh"), to my urls.py it runs on page load rather than on the button click.
I meat by that : the onclick callback of your button should fetch to url url of your django app. also you should use path('sets', views.setrefresh , name="setRefresh") instead of path('sets', views.setrefresh(), name="setRefresh") . it is running on page load because you were already invoking it by saying views.setrefresh()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.