4

First of all, I am new with Django, and pretty much completely unfamiliar with AJAX and jQuery. I am developing locally.

So I'm trying to achieve a HTML table, that is dynamically refreshed(without page refresh) every X amount of seconds with help from AJAX, but I can't seem to get my code to work. I've already used the example provided in this question: https://stackoverflow.com/a/34775420/6724882

(If I had enough rep, I would have either replied to that question, or asked help from chat, but I don't have that luxury yet)

I've been trying to get this to work for 10+ hours, and I start to feel helpless. I've been searching the web like crazy, but I'm overwhelmed by all the different ways of doing this, and every question and answer seems to be either too many years old, or just not relevant to my app.

At the moment, the table works correctly for the first query, it displays object Kala with rivinumero = 1 (rownumber in english).

So, I got couple questions.

  • Should I include the script in its own separate file, and not in the HTML file (in my case, displaykala.html). If so, should that file be in the static/js folder, or somewhere else?
  • Do I need to include AJAX/JS somewhere separately, in order for the script to work?
  • Am I clearly doing something wrong, or is the answer in the question I provided wrong?

displaykala.html(with the script in the same file)

{% load static %}
{% include 'loginbar.html' %}
{% include 'nav.html' %}
<html>
    <head>
        <title>Display</title>
        <link rel="stylesheet" type="text/css" href="{% get_static_prefix %}css/style.css">
    </head>
    <body>
            <h1>Display</h1>
            <table id="_appendHere" class="table table-striped table-condensed">
                        <tr>
                          <th>Id</th>
                          <th>Nimi</th>
                          <th>Latnimi</th>
                        </tr>
                        {% for kala in kalat %}
                        <tr>
                          <td>{{kala.rivinro}}</td>
                          <td>{{kala.tuote}}</td>
                          <td>{{kala.latinalainen_nimi}}</td>
                        </tr>
                        {% endfor %}
                      </table>
    </body>
</html>

<script>
    var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: {% 'get_more_tables.html' %},  // URL to your view that serves new info
            data: {'append_increment': append_increment}
        })
        .done(function(response) {
            $('#_appendHere').append(response);
            append_increment += 10;
        });
    }, 1000)
</script>

get_more_tables.html

{% load static %}
{% for kala in kalat %}
<tr>
   <td>{{ kala.rivinro }}</td>
   <td>{{ kala.tuote }}</td>
   <td>{{ kala.latinalainen_nimi }}</td>
</tr>
{% endfor %}

views.py

from django.shortcuts import render
from adminside.models import Kala
from adminside.models import Liha
from django.contrib.auth.decorators import login_required
# Create your views here.

def index(request):
    return HttpResponse("Index")

@login_required
def displaykala(request):
    kalat = Kala.objects.filter(rivinro=1)
    return render(request, 'displaykala.html', {'kalat': kalat})

@login_required
def get_more_tables(request):
    increment = int(request.GET['increment'])
    increment_to = increment + 10
    kalat = Kala.objects.filter(rivinro=2)[increment:increment_to]
    return render(request, 'get_more_tables.html', {'kalat': kalat})

urls.py (one in app folder)

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^displayk$', views.displaykala, name='displayk'),
    url(r'^get_more_tables', views.get_more_tables, name='get_more_tables'),
]

I'm sorry if there are "Yeah, I tried doing it this way" kind of stupid experiments in the code.

Matrix166
  • 79
  • 3
  • 10
  • Sorry I'm not clear what is actually going wrong. It updates once and then stops, but you're expecting it to append a new set every 10 seconds - is that right? – Daniel Roseman Nov 29 '17 at 09:27
  • @DanielRoseman Yes Daniel. What I'm trying to accomplish, is that the code would first display the first object, then after the X amount of seconds, append the next object to the table. In this case, first the object with attribute rivinro, with value 1 (works), and then the next object with value 2 (nothing happens at the moment). – Matrix166 Nov 29 '17 at 09:30
  • Are you sure this is the real code? `{% url 'get_more_tables.html' %}` should cause a NoReverseMatch error, because the URL pattern is called just "get_more_tables" without the .html (as it should be). – Daniel Roseman Nov 29 '17 at 09:40
  • Yes, you found out one of those "I tried this thing" experiments. You are correct, it produced that error. At the moment, it does not produce errors, and looks like this: {% url 'get_more_tables' %} . However, updating still does not work. – Matrix166 Nov 29 '17 at 09:43
  • What does the browser tools network tab show? Is it just making one request, or are there repeated requests that give an error, or what? – Daniel Roseman Nov 29 '17 at 09:44
  • I did not even think of looking there, my bad. When I check the console (I'm using Chrome), I can see that it reports error like this: "Uncaught SyntaxError: Invalid regular expression flags displayk:40 " Inside that, it display the specific line as: "url: /user/get_more_tables, // URL to your view that serves new info" – Matrix166 Nov 29 '17 at 09:47
  • Might be as simple as putting that in quotes: `url: "{% 'get_more_tables.html' %}",` – Daniel Roseman Nov 29 '17 at 09:53
  • That helped, and I've progressed into the next problem. Now I'm facing errors, no matter what I do. The line with the problem is in views -> def get_more tables. This line: ** increment = int(request.GET['increment']) ** causes this error: **django.utils.datastructures.MultiValueDictKeyError: "'increment'"** – Matrix166 Nov 29 '17 at 10:19
  • Your JS is sending the value as `append_increment` but the Python is trying to access `increment`. – Daniel Roseman Nov 29 '17 at 10:37

1 Answers1

1

Thank you so much @DanielRoseman. "Your JS is sending the value as append_increment but the Python is trying to access increment. – "

I changed the line in question to increment = int(request.GET.get('append_increment')) and it fixed the error, and now the table is dynamically updating. Thank you so much for spending your valuable time. Now I can keep building the app!

Matrix166
  • 79
  • 3
  • 10
  • Hello, After 2 years, I have stumbled apon similar problem ... my question is, why do you increment it by 10 ? lets say you have 12 things in db thats Kala model ... you will print out first 10 and then 2 .. after that you will need to wait until you have 20/21 things in your Kala and then you will print only 1 and not other 9 ... am I correct on this or am I missing something ? Thanks in advance :) – StyleZ Nov 30 '19 at 19:44
  • Hi there! it's been a long while since I worked on that project, but IIRC the information was supposed to be printed on a TV-screen, and we decided that 10 Kala things was a good amount of stuff on the screen, before switching to the next "page". It was just a matter of readability for the end-user :) If you think there's something else wrong in the code I posted, it was most likely fixed after I received the solution here. Hope you found a solution for your problem! :) – Matrix166 Dec 09 '19 at 07:30