How can I check if url_for references an existing file? - flask

I am serving pictures from a loop. Some of the referenced URL's do not exist though. In that case I want to reference to a default pic.
I tried
{% for hit in hits %}
{% if url_for('static', filename='pictures/' + hit['jpg']) %}
<img class="rounded-circle article-img" src="{{ url_for('static', filename='pictures/' + hit['jpg']) }}">
{% else %}
<img class="rounded-circle article-img" src="{{ url_for('static', filename='pictures/' + 'default.jpg') }}">
{% endif %}
{% endfor %}
which seemed to be a bit naive since it didn't change anything. Do you have an idea for a good way to handle this?

You can always chose the right image path before rendering the template. So maybe something with os.path.isfile:
import os
from Flask import render_template
...
for i in range(len(hits)):
if not os.path.isfile('relative/path/to/pictures/' + hits[i]['jpg']):
hits[i]['jpg'] = 'default.jpg'
render_template('/my/template.html', hits = hits, ...)
Template:
{% for hit in hits %}
<img class="rounded-circle article-img" src="{{ url_for('static', filename= 'pictures/' + hit['jpg']) }}">
{% endfor %}

Related

how to split a for loop in django

I want have a simple model for images. there is a option to upload unlimited images. but I want don't want them to be shown under each other. for instance just show the first 5 images then some text and then again another 5.
right now my code is like this:
{% for img in images %}
<img src="{{ img.images.url }}" class="img-fluid" alt="">
{% endfor %}
I want the Structure to be like this:
for loop for img0 to 5,
then everything elese,
then another for loop for img6 to 10,
Thanks for the solutions and apologies for my bad English
You can work with the |slice template filter [Django-doc]:
{% for img in images|slice:":5" %}
<img src="{{ img.images.url }}" class="img-fluid" alt="">
{% endfor %}
…
{% for img in images|slice:"5:10" %}
<img src="{{ img.images.url }}" class="img-fluid" alt="">
{% endfor %}

How break cycle for with if else statement in django template

I read if else statement in Django docs
but i don't understand my case.
I have photos list, i want render image if is COVER else i want render static image.
This my code
{% for x in listing.photos.all %}
{% if x.photo_tipo == 'COVER' %}
<img src="{{ x.get_thumb }}" alt="">
{% else %}
<img src="{% static 'images/about/1.jpg' %}" alt="">
{% endif %}
{% endfor %}
Result is: an image if x.photo == 'COVER' and a static image for every other photo in the list.
I would like to get only one result if the declaration is true or only one static image if it is false
Don't do this in the template. Add some logic somewhere that gives you the photo with that type directly if it exists. A good way would be with a method on the Listing model:
class Listing(models.Model):
...
def cover_photo(self):
return self.photos.filter(photo_tipo='COVER').first()
Now your template could be:
{% with photo as listing.cover_photo %}
{% if photo %}
<img src="{{ photo.get_thumb }}" alt="">
{% else %}
<img src="{% static 'images/about/1.jpg' %}" alt="">
{% endif %}
{% endwith %}

Sorl-Thumbnail static image in default

I use Sorl-Thumbnail in my django-project. I have a situation, when I havent got an image and I need to show no_image.png.
This code works:
{% thumbnail car.default_picture.image|default:"http://example.com/img/no_image.png" "240x180" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
But I want to use {% static "img/no_image.png" %} in default. I have an error:
TemplateSyntaxError: Syntax error. Expected: ``thumbnail source geometry [key1=val1 key2=val2...] as var`
How to fix it? Thanks.
I just found this alternative too:
{% thumbnail product.logo "200x200" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% empty %}
<img src="{% static 'images/default.gif' %}" width="200" height="200">
{% endthumbnail %}
{% if car.default_picture.image %}
thumbnail
{% else %}
{% static "img/no_image.png" %}
{% endif %}
It works for me

How to access Django/Mezzanine gallery content in a different page template

Can I access content from Mezzanine page gallery in a template I use for another page?
For example I have a gallery page that shows a collection of images I have added in Django Admin to the "Media Library". The page works fine and shows all of the images I have selected for the page.
The gallery page template has some code for displaying the images that looks something like...
{% with page.gallery.images.all as images %}
{% for image in images %}
<li>
<a class="thumbnail" rel="#image-{{ image.id }}" title="{{ image.description }}" href="{{ MEDIA_URL }}{{ image.file }}">
<img class="image-overlay-thumb" src="{{ MEDIA_URL }}{% thumbnail image.file 75 75 %}">
</a>
<div id="image-{{ image.id }}" class="image-overlay" style="display:none;">
←
→
<img class="image-overlay-full" src="{{ MEDIA_URL }}{% thumbnail image.file 0 600 %}"><br>
<p>{{ image.description }}<br>{{ forloop.counter }} / {{ images|length }}</p>
</div>
</li>
{% endfor %}
{% endwith %}
However, on a different page, I want to use those same images, in the same sequence within a list I'll use to drive a jQuery slideshow.
Is there a way to use a template tag something like '{% with page.gallery.images.all as images %}' but make it point to the specific page that has the gallery images I want?
Thanks in advance for any insight you can provide.
you need to create context processor like:
def all_pages(request):
from mezzanine.galleries.models import Gallery
galleries = Gallery.objects.all()
return {'pages': galleries}
then add it to your settings.py in TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'path.to.our.just.created.context_processor.all_pages',
)
then in template:
{% load mezzanine_tags %}
<ul class="thumbnails gallery">
{% for page in pages %}
{% with page.gallery.images.all as images %}
{% for image in images %}
<li>
<a class="thumbnail" rel="#image-{{ image.id }}" title="{{ image.description }}" href="{{ MEDIA_URL }}{{ image.file }}">
<img class="image-overlay-thumb" src="{{ MEDIA_URL }}{% thumbnail image.file 75 75 %}">
</a>
<div id="image-{{ image.id }}" class="image-overlay" style="display:none;">
←
→
<img class="image-overlay-full" src="{{ MEDIA_URL }}{% thumbnail image.file 0 600 %}"><br>
<p>{{ image.description }}<br>{{ forloop.counter }} / {{ images|length }}</p>
</div>
</li>
{% endfor %}
{% endwith %}
{% endfor %}
</ul>
I'm not so familiar with mezzanine, but it should work, you can pass context in view or other way and manipulate it.
you can also use templatetag like this:
#register.simple_tag
def show_gallery_by_slug(slug):
from mezzanine.galleries.models import Gallery
gallery = Gallery.objects.filter(slug=slug)
template = get_template("pages/images.html")
c = Context({"gallery": gallery})
return template.render(c)
and then in templates
{% load yourtags %}
{% show_gallery_by_slug "galleryslugishere" %}
you also need to create template to display with for image in gallery..

How to thumbnail static files?

I want to resize my static files with sorl thumbnail but it doesnt work
here is my codes
{% if not new.photo %}
{% with path="{{STATIC_URL}}/images/empty-news.jpg" %}
{% thumbnail path "80x80" crop="center" as im %}
<img alt="" src="{{im.url}}" class="frame2">
{% endthumbnail %}
{% endwith %}
{% else %}
{% thumbnail new.photo "80x80" crop="center" as im %}
<a href="{% url news_detail new.slug %}" class="image">
<img alt="" src="{{im.url}}" class="frame2"></a>
{% endthumbnail %}
{% endif %}
If I have image it shows image but when I dont have image I cant use default image because thumbnail doesn't work
Ugly option that worked for me, passing in the path that you would normally pass to the static template tag (note that it assumes the http protocol, so it could be improved):
{% with 'http://'|add:request.get_host|add:STATIC_URL|add:image_path as path %}
{% thumbnail path "720x306" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
{% endwith %}
This works by building up the absolute path to the static image.
Honestly...this looks fine; which means there is probably something simple wrong in your setup.
Possible bad setup:
How are you defining STATIC_URL in your settings? Also, what is the value of DEBUG (make sure this is set to True if you're developing locally)? As #goliney pointed out, your path might be messed up. Try pulling out the thumbnail blocks out, and set the src of your image to {{ STATIC_URL }}/images/empty-news.jpg and verify that works before trying to do the thumbnails.
Forgot to load thumbnails: Make sure to put {% load thumbnail %} in your template before any references to the {% thumbnail %} block.
The following will work
{% with STATIC_URL|add:"/images/empty-news.jpg" as path %}
{% thumbnail path "80x80" crop="center" as im %}
<a href="#" class="image">
<img alt="" src="{{im.url}}" class="frame2"></a>
{% endthumbnail %}
{% endwith %}
I'm working through the same issue myself. It seems that if you want to use STATIC_URL in your templates you'll need to make sure that path you pass to the thumbnail tag is absolute (treating the path as if it were external.)
Apparently the relative paths only work for images within the MEDIA_ROOT, seemingly designed for images coming from models.
As a test, try typing in the full http path.
See:
http://sorl-thumbnail.readthedocs.org/en/latest/examples.html
To cover a little more the uglyness i made a custom filter, using a constant in settings.py
SITE_URL:
settings.py
[...]
SITE_URL = "google.it"
[...]
templatetags/staticthumb.py
from django.conf import settings
from django import template
register = template.Library()
#register.filter()
def static_url(value):
return ''.join(["http://", settings.SITE_URL, settings.STATIC_URL, value])
Then to use it in the template:
{% load thumbnail staticthumb %}
{% with image_path|static_url as path %}
{% thumbnail path "720x306" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
{% endwith %}