Refreshing images on a page without refreshing the whole page with Django - python

I'm making an application that receives images.
I'm making it in a pretty hacky way, where this is the HTML:
<body onload="javascript:setTimeout('location.reload(true);', 1000);" >
<div class="container">
<img class="img0" src="{{ uno }}"/>
<img class="img1" src="{{ dos }}"/>
<img class="img2" src="{{ tres }}"/>
</div>
</body>
And this is in views.py:
def main(request):
x = get_newest_pics()
uno = x[-1]
dos = x[-2]
tres = x[-3]
context = { 'uno' : uno, 'dos' : dos, 'tres' : tres }
return render(request, 'index.html', context)
I'm sure there's a better way to go about this, but I'm very new to Django and I don't know how. At this point, the page is just flickering every second showing the same images, when really I just want it to refresh whenever there is a new image. Is there a way to consistently call get_newest_pics() and refresh just the images, rather than the whole page? Or even just a way to make the page stop flickering?

The way to do this is to implement ajax on your front end, and then request for new images at an interval, once a new image is found, update the container where you are showing your images and add the new (available) image.
Have a look at the django-dajaxice library to help you with the "wiring" of your front end to django correctly.
The way you have written your code, all three images are sent at once to your page, and your javascript snippet is in effect just refreshing the page very quickly, which is why you see the flickering effect.
You could do a "hack" and create a separate view for each image in django, then call each view on an interval using javascript - it would have the same end result but really inefficient in terms of code.

Related

Plotly + ajax - plot is not rendered

I have a django based web application; and I am using the Python wrappers of plotly to generate plots. When I try to use "ajax style" to fetch only the plot into a <div> </div> with a javascript call no plot is rendered. My situation is as follows:
<head>
<script>
async function generate_plot() {
const url = "/path/to/plot/generator/";
let response = await fetch(url);
let data = await response.text();
let element = document.getElementById('plot_div');
element.innerHTML = data;
}
</script>
</head>
<body>
<div id="plot_div"> </div>
...
</body>
At the /path/to/plot/generator/ endpoint there is a python function which looks like:
def plot_generator(request):
...
return plotly.offline.plot(fig, include_plotlyjs=False, output_type="div")
I am quite certain this is basically sound, because when I manually paste the return value from plot_generator() into <div id="plot_div"></div> the plot is displayed correctly, and also If I let the plot_generator() just return a dummy text like: This should have been a plot - the text is correctly displayed. But the plotly plot is not displayed in any way - the Firefox debug console shows no warnings/errors/anything ...
Something trivially wrong?
Update: When looking in the firefox console the plotly generated content seems to have arrived correctly in the browser/DOM.

Images Don't Display After Making Layered Webpage

I am using python, html, jinja, java script ect. to build a webapp on a raspberry pi powered device. So far when I put images on my webpages everything works fine. However when I create a "layered" webpage that is using a variable to differentiate between user profile files, it breaks my local image references which wont load and instead display their tag. Using online images for the image source works perfectly fine however.
Not Working Code(Python):
#app.route('/adminPortal/<user_id>', methods=['GET', 'POST'])
def adminPortal(user_id):
print('Admin Portal')
...
Working Code(Python):
#app.route('/adminPortal', methods=['GET', 'POST'])
def adminPortal():
print('Admin Portal')
Unchanged HTML:
<img src="{{ 'static/oldLady.jpg' }}" alt="Profile Pic Of User" height=200px> <span style="display:inline-block; width: 50px;"></span>
<img src="{{'static/' + avatar + '.png'}}" alt="Picture of Avatar" height=200px> <br>
<img src="https://api.time.com/wp-content/uploads/2021/06/Pills.jpg" alt="Picture of Avatar" height=200px> <br>
<img src="{{'static/Amy.png?' + time}}" width="240" usemap="#amymap" class="unselectclass">
So far I have not been able to find any success how I reference the photos, and I don't know how to create the same webpage infrastructure in any other manner than the "layered" system I have set up.
The URL static/oldLady.jpg means "relative to the directory with the current page". If you are rendering /adminPortal, then it means /static/oldLady.jpg. If you are rendering /adminPortal/joe, then it means /adminPortal/static/oldLady.jpg.
The solution is to use absolute URLs: /static/oldLady.jpg.

Embeded pdf File is not displaying in Django

I was trying to display photos and pdf files in a django project using <embed> but pdf file is not displaying
Here is what i was doing
This is view function
#login_required
def view_documents(request):
students = Student.objects.filter(user=request.user)
return render(request, 'student/view_documents.html',{'students':students})
and then I used for tag in template
{% for student in students %}
#lines of code
{% endfor %}
and to display the pdf file i have used
<embed src="{{student.adhar_card_pdf.url}}" width="800px" height="400px" type="application/pdf"/>
but it was showing some kind of error like localhost refused to connect
i also used iframe
<iframe src="{{student.adhar_card_pdf.url}}" style="width:718px; height:700px;" frameborder="0"></iframe>
But image is displaying in the browser using same code without any error
<embed src="{{student.photo_jpg.url}}" width="230px" height="250px" />
Why pdf file is not displaying ?? Please help me
Thanx in advance.
Edited: In console it is showing -- Refused to display '' in a frame because it set 'X-Frame-Options' to 'deny'.
This is how it is displaying pdf
X_FRAME_OPTIONS = 'SAMEORIGIN'
Insert the above line in settings.py just before the MIDDLEWARE section
and for the file path in embed tag write path as
{{student.file.get.photo_jpg.url}}
And then give a hard reset in Chrome or any browser you are using.
It worked for me I hope it works for you as well.

Dynamically update image using Python Flask AJAX

I have 1 very simple web application I am building right now but am very new to flask and jinja (and web development as a whole actually).
I have a watch folder, which will be getting an image sent to it via ftp on a pulse for ever. This wtch folder will only ever have one image in. Every 1 minute, the old image is replaced by a new image, with a new timestamp.
I would like to dynamically update the page, (and displayed timestamp) on a pulse as well, without having to reload any banners or static images that I will add later. I only want to update the following two lines out of the "Channels.Jinja" sample to follow.
<br>{{screenshot_datetime}}<br/>
<img src={{screenshot_location}} width="100%"/>
Channels.Jinja
<!DOCTYPE HTML>
<html>
<head>
<title>Training</title>
</head>
<body bgcolor=white>
<div id=main>
<br>Date and Time of Screenshot <br/>
<br>{{screenshot_datetime}}<br/>
<img src={{screenshot_location}} width="100%"/>
</div>
<div id='test'>
<p>
<script>
var myVar=setInterval(function(){get_image()},1000);
function get_image() {
$.ajax({
type: 'GET',
cache: false,
url: 'get_data',
success: function({{data}}) {
$('img').attr('src', data);
}
});
}
</script>
</p>
</div>
</body>
</html>
Channels.py
def render_channel_route(cr):
static_folder = os.path.join('static',cr)
file_list = os.listdir(static_folder)
channel_files = [f for f in file_list if f.startswith(cr)]
if not channel_files :
logger.error('Could not find image file for Channel. File should start with {0}'.format(cr))
abort(404)
img = os.path.join(static_folder,file_list[0])
ts = get_time_from_filename(file_list[0],cr)
return render_template('Channels.jinja',screenshot_datetime=time.strftime('%c',ts),screenshot_location=img)
#app.route('/channel01-10')
def first_tab():
return render_channel_route('channel01-10')
#app.route('/get_data', methods=['GET'])
def get_data():
return render_template('Channels.jinja',
screenshot_datetime=time.strftime('%c',ts),screenshot_location=img)
Im at a loss, Ive been bumbling around for a while now. Any and all advice is welcome! I am seeing a 304 response upon refresh, but not even the timer i am trying to put on it is working. Pardon sloppy code, highly volatile code is getting changed often -_-
I don't know it there is a "special" way to deal with Ajax using some Flask extension, but in the "normal" Ajax flow first you need to use url_for to put the correct url in your Ajax call and return the data formatted in some way (in my example in JSON) and not to render the template again:
$.ajax({
type: 'GET',
cache: false,
url: "{{ url_for('get_data') }}",
success: function(resp){
$('img').attr('src', resp.url);
$('#sst').html(resp.time);
}
});
So, in your get_data function in your controller you have to get the time and the path again for your image an then return some like this (to fit in my example before):
from flask import json
#app.route('/get_data', methods=['GET'])
def get_data():
#get time and path
time=...
path=...
return json.dumps({time:time,url:path}), 200, {'Content-Type':'application/json'}
Look that I use $('#sst') so you have to put in your HTML:
<br><span id='sst'>{{screenshot_datetime}}</span><br/>

Calling function on unlike event of facebook

I have been calling a function to run a query in to the database on a like event of facebook like button on my python site .And it is working absolutely fine .
FB.Event.subscribe('edge.create', function(href, widget)
But the problem is I need to use a another query of update on unlike event of the facebook button.
<script>
FB.Event.subscribe('edge.create', function(href, widget) {
top.window.location = 'http://pydev.abc.com/surpriseme/';
});
</script>
<div class="suprise">
<div class="suprise_con">
<div class="fb-like" style="overflow:hidden;" data-href="https://www.facebook.com/VivaAviesta" data-send="false" data-layout="button_count" data-width="100" data-show-faces="false"></div>
<span style="margin-left:5px;"> Like Us to Reveal</span>
</div>
</div>
For the url surprise me I have added a functionin views :
def surpriseme(request):
if request.user.is_authenticated():
cursor = connection.cursor()
cursor.execute("INSERT "......." (name,facebook_id,category,user_id) VALUES ('Abcd',1,'',%s)",[request.user.id])
#return HttpResponse("success")
return redirect("/showroom/")
Can anyone help in calling another function at the unlike event?
Actually the thing is that the person who has not liked the face book button on our site will not be able to see few of the products and once he/she hits like button they can see the products.
Now what I need is if anyone again unlike the button will should not be able to see products , which is not working at the moment.
calll like this
<script type="text/javascript">
window.fbAsyncInit=function() {
FB.Event.subscribe('edge.remove', function(href, widget) {
top.window.location = '{{baseurl}}/surprisemeunlike/';
});
FB.Event.subscribe('edge.create', function(href, widget) {
top.window.location = '{{baseurl}}/surpriseme/';
var url = '{{baseurl}}/surpriseme/';
});
}
</script>
Ok I got the answer, there is another event fron facebook :
FB.Event.unsubscribe('edge.create', handleResponse);
We can call another function on this event .
<script>
FB.Event.unsubscribe('edge.create', function(href, widget) {
top.window.location = 'http://pydev.abc.com/surpriseunlike/';
});
</script>
and it is working fine for me now .
"Like Gating" isn't against the terms of service and is used by many brands. It worked well under FBML, but it isn't reliable for an actual lockdown on the current API options. Facebook only prohibits requiring a like for contest entries (unless you use an approved vendor to run the contest).
If you actually want to require people to "Like" , you should be using their Graph API and 'realtime updates' https://developers.facebook.com/docs/reference/api/realtime/ Your javascript function will only work if someone likes or unlikes on that same page. It won't handle people liking or unliking in other browser windows or different time periods, which undermines your intent.
But if someone Likes your page and then unlikes it - so what? They already saw your special content.

Categories