django - Things to know about sorl-thumbnail - django

I am using sorl-thumbnail to create thumbnails for my project. I am implementing it only in templates and not in the models or the view. And each of the thumbnail are linked with their original image, which are used by a lightbox. As a newbie, I wanted to know, some of its functionality:
Whether implementing it only in the template is the same, as using it in the models or the view and creating a new thumbnail for each one?
How to configure different thumbnails for different image, as it can be done in easy_thumbnail?
How to override the default values, eg: override the value of Quality, etc.
And lastly, is it a correct way of implementing it? Any advice or suggestion will be much appreciated. Thank you.
html:
{% for photo in photos %}
<div class="thumbnail_container">
<a href="{{MEDIA_URL}}{{photo.image}}" class="gallery" title="{{photo.title}}">
{% thumbnail photo.image "200x200" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}" class="thumbnail">
{% endthumbnail %}
</a>
</div>
{% endfor %}
Edit:
How to achive something like this for the sorl-thumbnails, which can be done in easy-thumbnails:
settings.py
THUMBNAIL_ALIASES = {
'': {
'avatar': {'size': (100,100), 'crop': True},
'forum': {'size': (203,103), 'crop':False},
},
}
And then in the templates I can just chose from the aliases I have defined in the settings.py:
<img src="/static/{{forum.image |thumbnail_url:'forum' }}">
or
<img src="/static/{{forum.image |thumbnail_url:'avatar' }}">

Like many things in django sorl-thumbnail is implemented both simply and elegantly, and the way you are using it is correct.
Each time sorl-thumbnail is asked for a new thumbnail, it checks to see if one exists in its cache:
If one exists, this one is returned.
If it doesn't, a new one is generated and stored, then returned.
Thus, a cache of thumbnails are generated as required. The key,value store is a means of storing the thumbnails that makes them quick to look up and retrieve. Using the steps above the thumbnails will be generated and stored as they are requested by your users.
Thumbnail generation 'on demand' process works well, as images are added gradually to your website, the thumbnails for the new images will be created as required, and thumbnails for older images retrieved from the store.
To store the thumbnails Sorl-thumbnail uses a combination of a database and memory cache. The database ensures that all the thumbnails are saved should the app and or web server are restarted. The thumbnails will then be loaded into the memory cache (you guessed it) on demand, and thus ensure fast loading times for the user.
To answer your questions:
Whether implementing it only in the template is the same, as using it in the models or the view and creating a new thumbnail for each one?
It is not possible to generate the thumbnails in the models or views, as they are generated on demand, as the user requests them. This is very efficient. I guess you could write a script to request all the thumbnails, which was run on a nightly basis to ensure all the thumbnails are generated, although this is probably not required.
How to configure different thumbnails for different image, as it can be done in easy_thumbnail?
All configuration is done in the {% thumbnail %} tag, if different thumbnails for the same image are generated, these will be stored in the key, value store separately.
How to override the default values, eg: override the value of Quality, etc
There are a list of settings here: http://sorl-thumbnail.readthedocs.org/en/latest/reference/settings.html, these should all be set in the settings.py file. The Quality is set to 95 by default, which is pretty high.
Edit - set jpeg quality in settings.py
...
THUMBNAIL_QUALITY = 60
THUMBNAIL_PROGRESSIVE = False
...
These two additions, anywhere in the settings.py file for your project, will reduce the jpeg quality for the thumbnails to 60, and switch off the creation of progressive jpegs.
Edit - thumbnail aliases
There is no inbuilt support for thumbnail aliases in sorl-thumbnail. Probably the easiest way to implement them is as small sub templates, which can then be loaded into your main templates.
So a page template, might looks somthing like:
....
{% load thumbnail %}
....
<h3>Recent image uploads:</h3>
{% for item in recentUploads %}
{% include "bigThumbnail.html" %}
{% endfor %}
<h3>Older image uploads</h3>
{% for item in oldUploads %}
{% include "smallThumbnail.html" %}
{% endfor %}
....
The templates for the thumbnails would be stored as separate files in your template directory and could look something like:
bigThumbnail.html
{% thumbnail item.image "100x100" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
smallThumbnail.html
{% thumbnail item.image "40x40" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
In each of the sub templates, all the settings for your 'aliases' can be made. Alternatively, it would be possible to create an additional template tag to read these attributes from settings.py, this is what easy_thumbnail does, although would require a lot of programming to achieve the results of the 2 small templates above.
If you have further questions about sorl-thumbnail, I would be happy to help you with them.

Related

Check if image exists in Django template

I currently have a template that loops through a list of URLS, like so.
{% for i in images %}
<div class="col">
<p><img height="200" src="{{i}}"/></p>
<p>{{i|cut:"/uploads/"|truncatechars:20}}</p>
</div>
{% endfor %}
The issue is at the time of rendering some of the images are not done processing. So how would I check if the image is available via the url?
You'd have to make a custom tag or filter that evaluated the availability and sanity of the data. Perhaps using requests & pillow's .verify().
For a static "solution" you can provide a CSS fallback to your HTML img.

How to let the django thumbnail show me image?

Currenlty,I have learn django from the http://www.lightbird.net/dbe/photo.html and I meet a problem!I want show the thumbnail image on the 'Thumbnail item' but it's just show the html code:
<a href="/photos/1414.jpg><img border="0" alt="" src="/photos/1414.jpg" height="40"/></a>
I have define the class Image method like below:
def thumbnail(self):
return """<a href="/%s><img border="0" alt="" src="/%s" height="40"/> """ % ((self.image.name,self.image.name))
The attribute of Class Image have define like that:
class Image(Models.Model):
#The rest of another code
image=models.ManyToManyField(upload_to="photos/")
#....another code ..
I have check my path have create a photos on my project 'myweb/photos/'
How can i let the page understand it's html code .
First, I have no idea why you're using a ManyToMany field for this use case. You need to be using an ImageField.
The field you define as an ImageField will have a url property, which is what you use to reference the relative path to the file.
Second, don't mix HTML and Python in your model class. Django has templating specifically for this use case:
from django.template.loader import render_to_string
class Image(models.Model):
image = models.ImageField(upload_to='photos')
alt = models.CharField(max_length=100)
def thumbnail(self):
return render_to_string('thumbnail.html', {'image': self})
# thumbnail.html
<img src="{{ image.image.url }}" alt="{{ image.alt }}" ... />
Keep in mind that artificially scaling a full-size image to 40x40 pixels to generate a thumbnail is horribly inefficient, and if there are lots of these, will absolutely crush performance.
As others have mentioned, you can use excellent libraries like django-easy-thumbnails or sorl-thumbnail to generate proper, scaled down, optimized versions of these images at whatever dimensions you need.
please follow the tutorial on djangoproject.com ..the code on your link is not a right way use django,close it and read official docs
Use the url attribute instead of the name attribute on the image:
def thumbnail(self):
return """<a href="/%s><img border="0" alt="" src="/%s" height="40"/> """ % ((self.image.url,self.image.url))
There is also the excellent tool sorl-thumbnail. It helps with dynamically generating thumbnails in your templates. Install it with pip install sorl-thumbnail. You can use it like this:
template.html
{% load thumbnail %}
{% thumbnail item.image "100x100" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}

Resolve Static URL on Server

All of my user's have the option to link a profile picture. There are several templates that need to load this profile picture. If the user has not uploaded a picture, we use a default. When I want to display this profile picture, my code looks like this
<img src="{% if user.profile_picture.search_thumbnail.url %}{{ user.profile_picture.search_thumbnail.url }}{% else %}{% static "alternate.jpg" %}{% endif %}">
This is way too verbose for me, especially considering I need to repeat it out in multiple templates. I could use {% with %} blocks to store user.profile_picture.search_thumbnail.url, but that won't help me too much.
My solution was to write a function attached to the user model that returns the url of the static file. Unfortunately, the {% static %} is a template function. {% url %} has an equivalent function on the server called django.core.urlresolvers.reverse(). Does the alternative thing exist for the {% static %} tag?
In case anyone asks, I want to use the static function because my static files are stored in different places depending on the environment. My dev machine serves files locally, while my PRD machine serves static files from s3.
Thank you,
Nick
why not write a filter so you can do this.
<img src="{{ user.profile_picture.search_thumbnail.url|custom_filter }}">
and in the custom_filter you read from the settings.STATIC_URL to return the correct URL the user one is not set.
you could make the filter even shorter like this
<img src="{{ user|user_pic_url }}">
and in the filter pull out the .profile_picture.search_thumbnail.url /checks
This is what the static templatetag does underneath, and you can use it just fine in your own code:
from django.contrib.staticfiles.storage import staticfiles_storage
def static(path):
return staticfiles_storage.url(path)

sorl-thumbnail and image download

I have made a news portal with Django that news add manually in database. I have used sorl-thumbnail for news images. But the client wants to add news from an external source that received from json.
I have to save image name in database and download image. Could I use sorl-thumbnail in second way? Or I have to change my all upload system?
From sorl-thumbnail docs:
Using external images and advanced cropping:
{% thumbnail "http://www.aino.se/media/i/logo.png" "40x40" crop="80% top" as im %}
<img src="{{ im.url }}">
{% endthumbnail %}
It is likely that you will need to do some changes to your models, but as far as sorl-thumbnail goes, it should have no problems with external images.

Creating a thumbnail of an image on an external server

Let's say that someone has a link to an external image: www.externalsite.com/img/photo.jpg
Now, people can hotlink that image on my forum using [img] tags. A feature that is widely supported on almost every forum. Since hotlinking has some disadvantages I want to know how I can make a thumbnail of the image, based on the given url. Something Google does in Google images.
My website is powered by Django.
Use sorl.thumbnail
In your templates you would use
{% thumbnail "http://external.server/img/image.png" "200x200" "scale" as im %}
<img src="{{im.url}}" width="{{im.width}}" height="{{im.height}}">
{% endthumbnail %}
you can also load from any context varable
{% for image in post.images %}
{% thumbnail image.url "200x200" "scale" as im %}
<a href={{image.url}}>
<img src="{{im.url}}" width="{{im.width}}" height="{{im.height}}">
....