polyblog/imageapp/models.py

33 lines
939 B
Python
Raw Normal View History

from django.db import models
2018-02-18 19:51:16 +01:00
from uuid import uuid4
from django.utils.deconstruct import deconstructible
import os
from polysite import settings
2018-02-18 19:51:16 +01:00
@deconstructible
class UploadToPathAndRename(object):
def __init__(self, path):
self.sub_path = path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(self.sub_path, filename)
2016-10-24 19:56:22 +02:00
class BlogImage(models.Model):
title = models.CharField(max_length = 100)
caption = models.CharField(max_length = 300)
date = models.DateTimeField()
2018-02-18 19:51:16 +01:00
image = models.ImageField(upload_to = UploadToPathAndRename(""))
2016-10-24 19:56:22 +02:00
def __str__(self):
return self.title