Serving image files from the database to the template - python

I am stuck trying to figure out how to serve images files from a GET Request on a button in my html document; when the button is clicked it loads the image to the page. The files are stored in a directory for example: /model/modelrun/region/myimage.png I understand that the path to the image should be stored in the database:
page.html:
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<form action="#" method="GET" class="navbar-form navbar-left" role="form">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">GFS</button>
</div>
</form>
</div>
<iframe src="{% url 'new_model_image' }" ></iframe>
models.py:
from django.db import models
class NModels(models.Model):
model_name=models.CharField(max_length=30)
class Modelrun(models.Models):
currmodel = models.ForeignKey(NModels)
run_name = models.CharField(maxlength=20)
class MRegion(models.Models):
model_run = models.ForeignKey(Modelrun)
region = models.CharField(max_length=20)
class ModelImages(models.Model):
finalmodel = Models.ForeignKey(MRegion)
timestep = models.IntegerField(max_value=3)
picture = models.ImageField(upload_to=pathtomyimagefiles)
Reasoning: Every model will have multiple model runs of different regions where there will be multiple images for a given time step (maybe I need to separate these last two).
views.py:
def model_page(request):
if request.method =='GET':
[get image path and load into iframe]
return render(request, 'models.html')
Here's where I get lost with trying to use the GET request to get the path to the image to the database to load into the iframe.

Related

Flask: Bootstrap live search not working through render_kw in SelectField

My Flask web application form has a drop-down box with the list of all countries in the world. However, it gets tedious for the user to scroll and find the appropriate country they're looking for. Therefore, I'm trying to apply 'data-live-search' in my select fields for easier user navigation.
However, I'm trying to figure out the place I'm going wrong as my 'data-live-search=true' in select field does not yield any search box.
My codes are as:
routes.py (Flask Form)
def country_list():
return [('Angola','Angola'),('Andorra','Andorra').....] #All the countries
class Main_Form(FlaskForm):
countryList = SelectField("Enter the Country:", validators=[DataRequired()], choices=country_list(), render_kw={"data-live-search":"true"})
mainform.html
<div class = "container">
<fieldset>
<form class="form-group row" action="" method="post" novalidate>
<div class = "form-group col-md-12">
{{ wtf.form_field(form.countryList, class='form-control') }}
</div>
</form>
</fieldset>
</div>
When I look at the page source the data-live-search='true' appears for the select field but the drop-down does not contain any Search Box

Read a python rewritten image in Flask

I have code using Flask as given below:
app = Flask(__name__,static_url_path='/static')
#app.route('/')
def my_form():
return render_template('my-form.html')
#app.route('/result', methods=['POST'])
def result():
text = request.form['Name']
sentiment = generateimage(text)
return render_template("result.html")
my-form.html
<div class="col-lg-1"></div>
<div class="col-lg-10">
<form action="http://localhost:5505/result" method="POST">
<div class="form-group">
<label for="comment">Text</label>
<textarea class="form-control" rows="10" cols="4" id="comment" name="Name"></textarea>
</div>
<input type="submit" class="btn btn-info" value="Analyze">
</form>
</div>
</div>
result.html
<img src ="/static/fig1.png"/>
What flask.py does is grab the text from my-form, process it and generate an image in a static folder, but when the result.html page loads up it displays the previously generated image and not the most recent one.
How do I solve this issue?
def generateimage(text)
######some code######
plt.savefig('/home/aurora/Desktop/sentiment/static/fig1.png', dpi=dpi)
I'll assume that this is a caching issue, otherwise your first call to the system would not produce an image at all. A quick and dirty hack is to just force your image not to be cached by adding a random query string after the image URL within the result.html:
<img src ="/static/fig1.png?{{no_cache}}"/>
And then just call it from your Flask app as:
return render_template("result.html", no_cache=time.time()) # import time, of course
This, kind of, defeats the purpose of static content - if you're always going to render the image based on user input there is little point in storing it at all - just create a different Flask endpoint that will render the image directly to the user without ever storing it and call that instead of the image's static URL.

Pass the id of button from django template to a view

Below is my views.py file
def view_approval(request):
utype = request.POST.get('butn')
print utype
if utype == 'APP':
#certain set of funtions
if utype == 'SRC':
#certain set of funtions
else:
#certain set of funtions
And the HTML file:
<form name="feedback22" action="{% url 'view_approval' %}" method="post">
{% csrf_token %}
<input id="bdyBtn" type="button" name="butn" value="APP" data-toggle="modal" data-target="#appModal" >
<input id="bdyBtn" type="button" name="butn" value="SRC" data-toggle="modal" data-target="#srcModal" >
</form>
I have two modals in my HTML page, used for uploading two Excel sheets. So I created a Django view named view_approval and placed the code inside it. The code gets executed depending upon the input button clicked. But the issue is, the value of the input button is not reaching the views.
When I printed the value using a print inside the view, it showed a value "None"
Thanks in advance!!

Python / Django / Bootstrap - How to add images to the bootstrap carousel via website admin panel?

I have the following problem:
For now I have a working static bootstrap carousel with 3 images. The main idea is to add an app which allows to change these images via the website admin panel. Now I have:
model.py
class BGImagesModel(models.Model):
image1 = models.ImageField(upload_to='images/%Y/%m/%d')
image2 = models.ImageField(upload_to='images/%Y/%m/%d')
image3 = models.ImageField(upload_to='images/%Y/%m/%d')
admin.py
class BGImagesAdmin(admin.ModelAdmin):
list_display = ['image1', 'image2', 'image3']
admin.site.register(BGImagesModel, BGImagesAdmin)
url.py
urlpatterns = [
url(r"^$", "bg_images.views.images", name="images"),
]
views.py
def images(request):
context = {'context_images': BGImagesModel.objects.all()}
return render(request, 'index.html', context)
.html file is the following one. There are 3 main divs' for the images: the first one, where I tried to add an image via admin panel, just doesn't produce any image. The result is - empty. The second one and the third one (where images are hard-coded) do their job perfectly.
index.html
<div class="carousel-inner">
<!-- The first background image via admin panel-->
<div class="active item one">
{% for image in context_images %}
<div class="fill">
<div>
<img src="{{ image.image1.url }}" />
</div>
</div>
{% endfor %}
</div>
<!-- The second background image using inline CSS -->
<div class="item two">
<div class="fill" style="background-image:url({% static 'img/2nd.jpg' %});"></div>
</div>
<!-- The third background image using inline CSS -->
<div class="item three">
<div class="fill" style="background-image:url({% static 'img/3rd.jpg' %});"></div>
</div>
</div>
I've tried to find answer in the internet looking for the similar topics but didn't manage to do this.
One more time about the problem issue: having a try to add an image to the bootstrap carousel via website admin panel fails. An empty slide appears.
I would be really thankful for your help!
UPDATE
If I change my index.html like:
<!-- The first background image via admin panel-->
<div class="active item one">
<div class="fill">
<div>
<img src="{{ context_images.image1.url }}" />
</div>
</div>
</div>
then I get an empty page as well BUT with an icon of broken image in the upper-left part of the window. Using Firebug gives the following:
<div>
<img src="">
</div>
There is no queryset in the <img src="">. What the reason may it be?

How to handle delete in Google App Engine (Python)

I'm a newbie programmer and new to Google App Engine and webapp2 etc. So this may be a very basic question.
I am creating an application to store images into BlobStore. My model stores description, blob_key, image url and date.
I am able to save everything, so that bit is okay.
But now I want to create a delete button which will not only delete an item from the datastore, but also delete the image saved in the blobstore.
I have created a DeleteHandler, and in the html I have a form, passing the key for the item I want to delete. In the DeleteHandler, I am using the posted key to delete the item from the datastore. I am also trying to use the key to use it delete the image saved in the blobstore.
So far I'm getting a 404 on the delete form post, and even if I get past that, I'm not sure if my DeleteHandler is correct to handle the functionality I am looking for.
Any help would be much appreciated..
Main.py:
import os
import urllib
import webapp2
from google.appengine.ext.webapp import template
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import images
#Models
from google.appengine.ext import db
class ImageItem(db.Model):
description = db.StringProperty(required=True)
img_url = db.StringProperty()
blob_key = blobstore.BlobReferenceProperty()
when = db.DateTimeProperty(auto_now_add=True)
#Handlers (Views)
class MainHandler(webapp2.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload')
imgs = db.GqlQuery(
'SELECT * FROM ImageItem '
'ORDER BY when DESC')
imgs_dict = {'imgs': imgs}
self.response.out.write( template.render( 'main.html',locals() ) )
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
f = self.get_uploads('file')[0] # 'file' is file upload field in the form
img =ImageItem(description=self.request.get('description'))
img.blob_key = f.key()
img.img_url = images.get_serving_url( f.key() )
img.put()
self.redirect('/')
class DeleteHandler(webapp2.RequestHandler):
def post(self):
key = self.request.get('k')
item = db.get(key)
images.delete( item.blob_key )
item.delete()
self.response.out.write(key)
#URL Routing happens here
app = webapp2.WSGIApplication([('/', MainHandler),
('/upload', UploadHandler),
('/delete', DeleteHandler)],
debug=True)
Main.html:
<form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
<p>
<label for="file">Upload File</label>
<input type="file" name="file" id="file">
</p>
<p>
<label for="description">Description</label>
<input type="text" id="description" name="description">
</p>
<input type="submit" name="submit" value="Submit">
</form>
<ul>
{% for i in imgs %}
<li>
<img src="{{i.img_url}}=s400-c" alt="">
{{i.description }}
</li>
<li>{{i.when }}</li>
<li>
<form action="/delete" method="POST" enctype="multipart/form-data">
<input type="text" name="k" value="{{i.key}}" />
<input type="submit" value="delete">
</form>
</li>
{% endfor %}
</ul>
The deletes are close. Once you have a key, you can delete entities by calling db.delete(key).
For your example, this would be something like this:
class DeleteHandler(webapp2.RequestHandler):
def post(self):
key = self.request.get('k')
item = db.get(key)
blobstore.delete([item.blob_key])
db.delete(item)
self.response.out.write(key)
Your url handling in main.py is good, so it's not obvious to me why you're getting a 404. You could double-check your app.yaml file to make sure all urls are passed to main.py.
Here's a sample app.yaml handlers url section:
handlers
- url: /.*
script: main.app
Got it to work. Thanks Eric, yours was real close. I needed to use blob_key.key().
Final code is following:
class DelHandler(webapp2.RequestHandler):
def post(self):
key = self.request.get('k')
item = db.get(key)
n = item.blob_key.key()
blobstore.delete(n)
item.delete()
self.redirect('/')

Categories

Resources