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
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.
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.
Related
I from login page render to the admin index page, but the url address did not change, how to change it?
Code is below:
return render(request, 'app_admin/index.html')
As a common sense , all we know use render the url address do not change, but I want it change. how can I do that? I do not want to use the redirect, because I will pass data in render. how can I do that?
There is no way for the render to change the URL. Django uses the model-view-controller pattern, and the view has nothing to do with the URL. To achieve what you want you will have to redirect the user first, and then render on that route instead.
I see the URL on your page is /login so I assume this problem occur when you attempt to log the user in. If you reuse this approach (render upon receive submit form), you will run into problems sooner or later. For example, try to refresh the page you are currently displaying, I think the browser asks you to resubmit the form.
You say that you don't want to redirect because you pass data in the render. This is also an error prone approach. Store information consistently between pages with cookies and sessions. How would you otherwise store the login details when the user navigates the admin panel?
What you ask is not possible. The render function (with friends) has no option to change the URL.
You have to bind a separate url if you want to display in browser URL
For this
Add url for a index.hmtl and assign view to it
on action call just url what you specified
I currently have an extremely basic Python webapp. I am utilizing it to do some base tests against a SmartTV browser that doesn't support javascript even remotely well.
I need to be able to point the TV browser to the URL for my webapp, have it load a page containing a div with just a gif contained within, then say every 10 seconds, reload the page, switching to a different gif. It can be just two gifs that switch back and forth, but I need to figure out how to make this happen without Javascript reloading the page. Or perhaps with the very most basic javascript in the whole wide world to reload the page, but I've tried several js actions and met with various types of poor handling, resulting in unexpected results that, while interesting, did not test what I've been tasked with testing.
Here's my current code from app.py:
import web
import time
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
currentGif = 'http://10.111.0.221/onegif/cosmicShip.gif'
return render.index(currentGif = currentGif)
if __name__ == "__main__":
app.run()
The template that's calling is a simple div as described above, passing the URL to put up the gif as the background image. What I'd like to do is find some way to basically just add a sleep(10) after that return, switch currentGif to the second gif file, and return the page again.
I know doing it that way isn't reality, but it's the most simple way I can think to explain what I want. I just need to load the page ones, and have it loop between two pages until I manually exit, and I don't believe JavaScript is a viable option for this.
Any ideas?
I think you can use javascript to refresh in that amount of time and passing by GET params the ID of the page an then you at the python controller call the other page.
Javascript need it for the client part. Or reload or call an ajax function all the time with a sleep.
Python: Controller saving the state and respond with the corrent status.
Feel like I am stumbling over something fairly simple here.
I am not understanding something about AJAX and Flask.
I have a project wherein I display mongodb records in the browser, which has been working fine.
I added functionality for users to increment votes on a record; to Vote it up if they like it. But originally I was then refreshing the entire page with the new vote, using a redirect, which is clumsy. So I am trying to get AJAX to send the data over to the mongodb record and then update the span where I want the votes to appear without having to reload the entire page.
Problem is, the setup I have going, while still updating the record, is now loading a new page with the HTML i want returned only to the span where the vote tally should be (that is, it's loading a new page with only the word "test" in it (the test value I am currently returning)).
The jQuery (the library I am using) is loading fine and there are no other problems (as far as I can tell).
I have the relevant HTML and JS here:
<!-- All Standard HTML up here, removed for simplicity -->
<script>
$('#vote_link').bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$('#vote_tally').load(url);
});
</script>
<a href='/vote_up/{{ item._id }}' id='vote_link'>Vote for Me!</a><br>
Likes: <span id='vote_tally'>{{ item.votes }}</span>
<!-- All Standard HTML down here, removed for simplicity -->
and the python is here:
from flask import Flask, render_template, request, redirect, flash, jsonify
#from mongokit import Connection, Document
#from flask.ext.pymongo import PyMongo
from pymongo import Connection#, json_util
#from pymongo.objectid import ObjectId #this is deprecated
import bson.objectid
'''my pymongo connection - removed for simplicity'''
'''bunch of other routes - also removed for same reason'''
#increment a vote
#app.route('/vote_up/<this_record>')
def vote_up(this_record):
vandalisms.update({'_id':bson.objectid.ObjectId(this_record)},
{"$inc" : { "votes": 1 }}, upsert=True)
'''
also trying to return value for votes field from mongo record, but one step at a
time here
'''
#result = vandalisms.find({'_id':bson.objectid.ObjectId(this_record)}, {'votes':1})
result = 'test'
return result
I am also having trouble figuring out how to return the individual vote value for the specified mongodb record back to the browser, even with jsonify (which returns {"votes":'_id'}, but that's another issue. Hopefully someone can help me understand how to make AJAX work for me with Flask in this regard.
Thanks in advance,
Edit-24Jul2012-2:27PM CST:
I suspect that the jQuery isn't even activating. It seems to be loading the new page based on the link's href attribute, hence it's no use to have e.prevenDefault(); when that's not being run. Furthermore, an alert('I have been clicked'); never runs when the click event takes place. Again, the jQuery is loaded, but the click event is not activating the jQuery, and I don't know why not.
My guess (based on your edit) is that you have more than one element on the page with the ID of vote_link - this is not allowed in HTML (the ID property must be unique across the document). If you want to have multiple links sharing the same behavior use a class instead ($(".vote_link") for example).
Basically the way AJAX works is that the server replies with XML or JSON.
In this case jsonify function from flask will respond with a message with this HTTP header field:
Content-type: application/json
This is inorder for the Browser and JavaScript to understand the syntax, if you need to receive more than just a number or some text.
So, use jsonify on Flask as the docs example and then use $.getJSON() or $.ajax() on the JavaScript side.
http://flask.pocoo.org/docs/patterns/jquery/#json-view-functions
https://github.com/mitsuhiko/flask/tree/master/examples/jqueryexample
My website have submenus for sections. What I want to do is, when users click the submenu, the content changes accordingly. For example, if user clicks "Pen", the contents of the shall be list of pens, clicks "Eraser" , contents shall be eraser list.
How can I achieve this by using Django template and ajax? I know that I could retrieve the information as JSON data and parse it to update the div, but that requires a lot of work and I cannot use the Django template functionality.
I managed to pass the AJAX request to the server and process the list, but how can I return the rendered template as AJAX result?
Simply return the rendered template fragment. You don't need to do anything special. Your Javascript can then just insert it into the DOM at the relevant point.
I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.
I am using flask as my python framework, and normally I render templates doing somnething like the below:-
#app.route('/home')
def userhome():
data=go get user details from the database
return render_template("home.html",userdata=data)
Now I have a template name home.html in which I iterate over the values of "userdata" like userdata.name, userdata.age etc and these values take their appropriate spaces in the template.
However I am working on an application in which navigation is via ajax and no fall back if javascript is not available(basically the app does not work for ppl without javascript).
The navigation menu has say few tabs on the left ,(home,youroffers,yourlastreads). The right column is supposed to dynamically change based on what the user clicks.
I am unable to understand how I handle templating here. Based on what the user clicks I can send him the required data from the db via a json through an xhrGET or xhrPOST.Does the entire templating have to be handled at the server end and then transfer the entire template via an ajax call. I actually dont like that idea much. Would be great if someone could point me in the right direction here.
Now in the page that is loaded via ajax , there are some scripts which are present. Will these scripts work, if loaded via ajax.
You have two options: template on the server, or template in the browser.
To template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.
To template in the browser, your endpoint creates a JSON response. Then a Javascript templating library can take that JSON, create HTML from it, and insert it into the page. There are lots of jQuery templating solutions, for example.
I would choose server side templating, because unless you find a JS library that handles the same templating language your code isn't going go be DRY.
In the home.html template, I'd do something like
<%extends base.html%>
<%include _user_details.html%>
... <% footer and other stuff%>
And keep the actual markup in _user_details.html. This way, for an AJAX request you just render the _user_details.html partial only.