sorl-thumbnail doesn't generate placeholder images - django

I'm trying to upgrade a django project using the old sorl-thumbnail (v.3.2.5) to the newest (v.12.0) but I'm not able to get it generate placeholder images in development environment using the settings provided: http://sorl-thumbnail.readthedocs.org/en/latest/reference/settings.html#thumbnail-dummy
Here are my settings:
THUMBNAIL_DEBUG = True
THUMBNAIL_DUMMY = True
THUMBNAIL_DUMMY_SOURCE = 'http://placekitten.com/%(width)s/%(height)s'
MEDIA_URL = '/media/'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
This is the model using sorl ImageField:
from sorl.thumbnail import ImageField
class Cover(models.Model):
[... other fields here]
image = ImageField("immagine", upload_to='images/cover/%Y/%m/%d', max_length=255)
and the admin inherits from sorl.thumbnail.admin.AdminImageMixin.
The project uses Django 1.6 but I tried same settings on another project which uses Django 1.5.5 and I have the same problem.
Thumbnails are correctly generated (and retrieved from cache) for newly updated images, but pre-existent images are not substituted with placeholders, neither in admin nor in frontend pages (development server answers with a 404).
Any clues? Sorl docs are really scarce...

After searching through sorl-thumbnail code I found out that in the admin the THUMBNAIL_DUMMY setting is not even considered...
There is a pull request to solve this (opened a year ago): https://github.com/mariocesar/sorl-thumbnail/pull/128
As for the frontend it works, it was just a silly mistake in the template.

Related

Pytorch Model causing 500 server error in Django App

This is My Django project Directory, and in the "bills" app, I am trying to import my YOLOV5 pre-trained custom model (which works fine on its own).
So Views.py :
def crop(request):
model = torch.hub.load('../yolov5-master', 'custom', path='../best.pt', force_reload=True)
return render(request, '../templates/results.html')
This is causing my app to return a 500 server error when hitting that URL; I know the model is causing it because if I comment out that first line
#model = torch.hub.load('../yolov5-master', 'custom', path='../best.pt', force_reload=True)
Then the page shows fine.
I looked up many articles on how to load a Pytorch model into Django and it seems I am doing it right, can you please help me figure out what's the problem ?
I think the issue is related to path. You can try this in views.py:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yourappname.settings")
django.setup()
from django.conf import settings
model = torch.hub.load('../yolov5-master', 'custom', path=os.path.join(settings.MEDIA_ROOT, 'best.pt'), force_reload=True)
In your settings.py, you will first need to configure your MEDIA_ROOT path like this:
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_media')

Django Ckeditor Save incomplete data from richtextfield to cookies or server

The title, in my opinion, is self-explanatory. Basically let’s say a user if filling out an ckeditor richtextfield like so:
#app/models.py
from django.db import models
from ckeditor.fields import RichTextField
class App_Model(models.Model):
content = RichTextField()
Now let’s say an user left the page. The content will not be saved. I want the content to be saved, whether it be cookies or to the server, so the user can come back and pickup where he left off. How would I do this, preferably in the most simplest way possible.
Thanks.
One way to save the content is by using the CKEditor-AutoSave-Plugin
plugin for CKEditor 4, which saves the data in an HTML5 LocalStorage (client-side).
You just need to download and add that plugin to the django-ckeditor module.
Download and unpack the CKEditor-AutoSave-Plugin into your static directory. Make sure that you put the autosave folder from the archive into this directory:
<static-dir>/ckeditor/ckeditor/plugins/autosave
Where <static-dir> refers to the directory for your static files. This could be directly inside your app folder (next to admin.py, apps.py etc). For more details check the Django documentation.
Configure your CKEditor by adding this to your settings.py
CKEDITOR_CONFIGS = {
'default': {
'extra_plugins': ['autosave'], # Use the 'autosave' plugin
'autosave': { # Configuration on the autosave plugin
'autoLoad': True # Don't ask for confirmation to restore
}
},
}
For more configuration options check the documentation on GitHub.

DRF: Uploading images in Django

I have a profile database for users in which I save their profile image.
I am using DRF to create API's for this.
Now when I save the profile data, it return JSON as:
{
"branch": "CSE",
"year": 2014,
"image": "static/profile_images/abhishek.jpg"
}
this data gets saved in database and even the image get uploaded to the desired folder. Now I want to access this image in the frontend(I am creating an android app in Ionic), so that the profile pic is viewed in the app's dashboard. How do I do it?
At present simply going to the saved path is not working.
I found the answer what I was looking. Actually in Django files can be partitioned into two:
Static files: those files used in the development, creation and rendering of the website or app. Things like
stylesheets, scripts, fonts etc.
Media files: those files that are uploaded during the normal usage of the website or application such as images, pdfs,
videos etc.
So to have upload functionality one needs to add the following in the settings.py
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, '<folder-name>')
MEDIA_URL = '/media/'
and in urls.py add:
urlpatterns = [
.......
your urls
.......
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Installing TinyMCE on Django (And using it on forms)

Hi Im trying to install TinyMCE on a Django project and Im totally lost about static files, MEDIA, and the world itself.
I want to use TinyMCE in one of the fields of a form:
class MovieForm(forms.ModelForm):
class Meta:
model = Movie
fields = ['title', 'language', 'description']
widgets = {
'languages': forms.SelectMultiple(),
'description': TinyMCE({'cols':80, 'rows':30}),
}
I installed django-tinymce
pip install django-tinymce
Then I added it to the installed apps
INSTALLED_APPS = (
...
'tinymce',
...
)
And then added the urls in my project urls.py
urlpatterns = patterns('',
...
(r'^tinymce/', include('tinymce.urls')),
...
)
Great. So what do I do next?
I read the Configuration part on http://django-tinymce.readthedocs.io/en/latest/installation.html#configuration but I dont get it.
Should I add TINYMCE_JS_URL = os.path.join(MEDIA_URL, "path/to/tiny_mce/tiny_mce.js") to my project settings.py? Where do I put tiny_mce.js? Should I configure MEDIA_URL somewhere?
Would be awesome if someone can point me in the right direction.
Thanks! :)
I figured this, so I'm posting an answer in case anyone else comes across this.
I read more in details the documentation on Static files (https://docs.djangoproject.com/en/1.10/howto/static-files/), and read the related section of the great book Tango with Django (http://www.tangowithdjango.com/).
That helped me to understand the MEDIA and STATIC setup I needed to get right in order to get working TinyMCE with Django.
tiny_mce.js went to the static files folder (specifically to static/tiny_mce/).
The settings.py of Tinymce check if static is confidured, and points there to get the needed files. Tadaa! It works!
Hopefully it will help someone!

Django: sorl-thumbnail cache file is not deleted in production environment

I use django-cleanup, sorl-thumbnail in my Django project.
I have a model like this:
from sorl.thumbnail import ImageField
class Variation(BaseModel):
image = ImageField(upload_to=draft_img_upload_location)
And I use signal for sorl-thumbnail like this (recommanded by https://github.com/un1t/django-cleanup):
from django_cleanup.signals import cleanup_pre_delete
def sorl_delete(**kwargs):
from sorl.thumbnail import delete
delete(kwargs['file'])
cleanup_pre_delete.connect(sorl_delete)
So, In local environment, belows work:
1. When I delete Variation model in ADMIN PAGE, it deletes BOTH image file and image cache(created by sorl-thumbnail).
2. When I change just image file with other image in ADMIN PAGE, it delete BOTH 'prior image file' and 'prior image cache file(created by sorl-thumbnail)'.
In production environment, I used AWS S3 and cloudfront for managing static and media file. So all sorl-thumbnail cache image files are stored in S3. But whenever I changed the image file with other image file in ADMIN PAGE, the prior image cache file(created by sorl-thumbnail) still remained.
Lets say that sorl-thumbnail image url is https://example.cloudfront.net/cache/da/75/abcdefg_i_am_cached_image.jpg (from Google development tool).
In this case, there were two image files exist in S3: abcdefg.jpg and /da/75/abcdefg_i_am_cached_image.jpg
I changed abcdefg.jpg with the other image. Then, it completely deleted abcdefg.jpg in S3 storage.
Now, I accessed https://example.cloudfront.net/cache/da/75/abcdefg_i_am_cached_image.jpg in my browser and guess what! It showed this sorl-thumbnail cached images in this time!
Strange thing happened in S3 storage. When I tried to check whether abcdefg_i_am_cached_image.jpg exists in path /da/75, there was no directory named 75 right below the da folder!
In short, abcdefg_i_am_cached_image.jpg still remained in my S3 storage!
I don't know why this happened only in production environment...
This is part of settings only for production mode.
settings.py
from .partials import *
DEBUG = False
ALLOWED_HOSTS = ["*", ]
STATICFILES_STORAGE = 'spacegraphy.storage.S3PipelineCachedStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN = os.environ.get("AWS_S3_CUSTOM_DOMAIN")
AWS_S3_URL_PROTOCOL = 'https'
AWS_S3_HOST = 's3-ap-northeast-1.amazonaws.com'
STATIC_URL = "https://this-is-my-example.cloudfront.net/"
INSTALLED_APPS += [
'storages',
'collectfast'
]
AWS_PRELOAD_METADATA = True
storage.py
from django.contrib.staticfiles.storage import CachedFilesMixin, ManifestFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineManifestStorage(PipelineMixin, ManifestFilesMixin, S3BotoStorage):
pass
class S3PipelineCachedStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
After spending couple of hours debugging, I found out that sorl_delete signal is not called only in production environment!!.
I have no idea why this happened. I think that this one is a main problem.
And sorry for bad english (I'm not native). Really need your help. Thanks