Skip to content

Instantly share code, notes, and snippets.

@sehmaschine
Created November 23, 2015 12:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sehmaschine/8ec052d7423dbd307fce to your computer and use it in GitHub Desktop.
Save sehmaschine/8ec052d7423dbd307fce to your computer and use it in GitHub Desktop.
Signals for FileBrowseUploadField
from apps.images.signals import image_callback
def entry_upload_path(instance, filename):
return os.path.join("uploads", "blog", str(instance.id), filename)
class Entry(models.Model):
image = FileBrowseUploadField(max_length=250, upload_to=entry_upload_path)
post_save.connect(image_callback, sender=Entry)
def image_callback(signal, sender, instance, created, using, **kwargs):
"""
Move temporary Images
"""
import os
from django.conf import settings
from django.core.files.move import file_move_safe
from django.utils.encoding import smart_text
opts = instance._meta
fields = [f.name for f in opts.fields]
if "image" in fields and instance.image:
try:
filename = os.path.basename(smart_text(instance.image)).split("__")[1]
except:
filename = os.path.basename(smart_text(instance.image))
upload_to = opts.get_field("image").upload_to(instance, filename)
if "/_temp/" in instance.image.path:
new_file = get_available_name(os.path.join(settings.MEDIA_ROOT, upload_to))
new_path = os.path.split(new_file)[0]
if not os.path.isdir(new_path):
os.makedirs(new_path)
os.chmod(new_path, 0775)
file_move_safe(os.path.join(settings.MEDIA_ROOT, instance.image.path), new_file, allow_overwrite=False)
os.chmod(new_file, 0775)
instance.image = new_file.replace(settings.MEDIA_ROOT + "/", "")
instance.save()
# now generate all versions for this image
for v in settings.FILEBROWSER_VERSIONS:
version = instance.image.version_generate(v)
os.chmod(os.path.join(settings.MEDIA_ROOT, version.path), 0775)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment