Home > OS >  Auto refresh HTML database data in Django - Ajax?
Auto refresh HTML database data in Django - Ajax?

Time:03-17

I have a Django server which is locally hosted and displays sensor data from a MySQL database. This data is displayed on the instruments.html page through variables such as {{qs.value}} which comes from the views.py, models.py and URLs.py. The views.py page is as follows:

from django.http import HttpResponse
from django.shortcuts import redirect, render
from .models import Sensorresult

def db(request):
    qs = Sensorresult.objects.using('Vision').get(sensorresult='1')
    return render(request, 'authenticate/instruments.html',{'qs':qs})

The problem I have is that I want the database information to update on the html every second, whereas currently it only updates when the page is refreshed. I know I could place a line of javascript at the top of the page and have the entire webpage constantly update, but I only want the database values to update. Does anyone have any suggestions as to how to do this?

From googling have come across Ajax, however this is something I have no experience in and I am unsure how my code would be edited to accommodate this?

Many thanks

CodePudding user response:

Instead of directly using fetched data in HTML, you can try fetching it in javascript.

And if you have ever created the clock with javascript, it does not reload the entire page but still updates the time. You can use the same way to update that fetched data in HTML.

CodePudding user response:

You may want to consider using htmx.

Very simple library which takes away the JavaScript complexity to update parts of a web page rather than a full page reload and allows you to do most of the work in html.

Their docs specifically make reference to polling to update a certain part of the page which seems to be exactly what you’re trying to achieve.

Essentially all you’d need to do is create a view that returns a template partial, then use htmx polling to hit that url and replace a div with the partial the view returns.

  • Related