0

I'm trying to update the div of a template with Django, so I use AJAX to refresh. The refresh works but during the first refresh, everything that was outside the div is doubled but only for the first refreshment . I've been blocking for quite a few days and I don't understand why, I applied the method found on this subject:Refresh a div to shows new rating in Django using JQuery and AJAX

So I include another page "update.html" which contains my variables to update. And with ajax, I refresh this page.

I'm sorry for the amount of code I provide, but I despair. Thank you for your feedback

My view.py

def RPI(request,rpi_id):
    form = ContactForm(request.POST or None)
    form2 = Boutons(request.POST or None)
    formtest= test(request.POST or None)
    Pactive = sql.run("Pactive") ## peut être passer en thread pour eviter l'attente de la nouvelle informaion et ralentir le code 
    Preactive = sql.run("Qreactive")
    Courant = sql.run("I")
    conf_thread = connect.conf()
    conf_thread.start()
    time.sleep(1)
    power,statut=conf_thread.getConf()
    val =""
    if form2.is_valid():
        val=form2.cleaned_data.get("btn")
        if val == "Start" : 
            connect.start()
        if val == "Reboot" :
            connect.reboot()
        if val == "Stop" :
            connect.stop()  
        if val == "Code" : 
            connect.code_util()
        if val == "fichier" : 
            print("fichier")
            #file.FilepathName
        if val == "Envoyer code":
            myfile = request.FILES['myfile']
            fs = FileSystemStorage(location='/home/opens/Bureau/appliweb/appliweb/ENVOI/')
            filename = fs.save(myfile.name, myfile)
            uploaded_file_url = fs.url(filename)
            print(uploaded_file_url)
            connect.envoi(uploaded_file_url)

    if form.is_valid():
        if val == "": ## a revoir
            msg = form.cleaned_data['message']
            message="RPI"+str(rpi_id)+","+str(msg)
            thread.reception(message)
            envoi = True

    return render(request, 'page/RPI.html',locals())

def update(request):

    return render(request, 'page/update.html',locals())

My update.html which contains my vairables to update:

<p>POWER : {{power}}<br>
Etat du programme : {{statut}}<br>
Puissance ACTIVE : {{Pactive}} W <br>
Puissance REACTIVE : {{Preactive}} VAR <br>
Courant mesurée : {{Courant}} A </p>

My RPI.html which contains my main page and include the update.html page:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/styleliste.css' %}">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
    <title>{% block title %}Liste des Raspberry Pi{% endblock %}</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
    <body class="bg2">  
        <ul>
            <li><a href="/page/accueil/">Accueil</a></li>
            <li><a href="/page/ListRPI/">Liste des Raspberry PI</a></li>
            <li><a href="/page/Info/">Plus d'informations</a></li>
            <li><a class="active">Raspberry PI {{rpi_id}}</a></li>
        </ul>
        <section id="contentinfo">
            <div id="update">
            {% include 'page/update.html' %}
            </div>
            <div>
                <form method="POST" >
                            {% csrf_token %}
                            {{ form.as_p }}         
                        <input class="ml-button-3" type="submit" value="Envoyer message"/>  
                </form>
                <form method ="POST" enctype="multipart/form-data">
                    {% csrf_token %}
                    <input class="ml-button-3" type="submit" name="btn" value="Start"  />
                    <input class="ml-button-3"type="submit" name="btn" value="Stop"  />
                    <input class="ml-button-3"type="submit" name="btn" value="Reboot" />
                    <input class="ml-button-3" type="submit" name="btn" value="Code" /> <br><br>
                    <input type="file" name="myfile">
                    <input class="ml-button-3" type="submit" name = "btn" value="Envoyer code"></button>
                </form>
            </div>
        </section>
    <script>
 $.ajax({
    url: 'http://localhost:8000/page/RPI/1/',
    success: setInterval(function(){
        alert('Vote successful!');
        $("#update").load("update.html");
    },5000)
});   
    </script>
</body> 
</html>

Kangting
  • 31
  • 8
  • you're not really explaining the behaviour you want. There's a form in your page. What exactly do you want to happen when the user submits the form? Please describe step by step what the user does and what he should see as a result. – dirkgroten May 17 '19 at 10:21
  • I want to have a web interface with buttons to remotely control a raspberry pi, and on this web interface I also want to display some measurements that they send back to me. So I have formats with buttons, this part of the code works very well, I also display the different measurements it sends me back, however, before, I refreshed the whole page periodically, but this prevents me from having time to send any file to the raspberry, so I only want to update the division of the measurements, but everything that was outside the div is doubled but only for the first refreshment – Kangting May 17 '19 at 11:15
  • ok, but right now this is what your code does: when the page is first loaded, the ajax script runs immediately fetching `/page/RPI/1/` with GET (it doesn't do anything with the response and then it tries to `load()` "update.html" but that probably gives an error because you it's normally not a valid url). When the user submits the form, your view re-renders the same page again (so the page refreshes) and your ajax call fires again. What do you mean "everything is doubled"? And what do you see happening in browser debug tools (console and network tab)? – dirkgroten May 17 '19 at 12:37
  • `$("#update").load("/")` is what will fetch the rendered template (you want to call your `update` view, not fetch the template as-is; I don't know the url, probably `/page/update`). Also there's no need to put it inside an `ajax` call (I don't see the purpose of your ajax call). – dirkgroten May 17 '19 at 12:45
  • When I say that it doubles, it means that I have two start stop buttons etc. only for the first refresh, then it refreshes correctly but the duplicates remain on the page. Is it more correct if I write this in my html script? – Kangting May 17 '19 at 15:10
  • `load('update.html')` is wrong because that's not the url to run your `update` view. you need to put the url in there (defined in urls.py). I'm quite sure using "update.html" raises a 404 'page not found' error in your javascript console. – dirkgroten May 17 '19 at 15:13
  • Oh I understood, my problem is solved, first as you said, I misreferenced my page in my script so it was rather : setInterval(function(){ $('#update').load('/page/update'); }, 5000); Then my variables in views.py were referenced in my RPI page and not in my update page. Now everything works. Thank you very much for your help, I understood better how it works, and I was able to solve the problem. – Kangting May 17 '19 at 15:18

0 Answers0