from __future__ import unicode_literals from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.db import models import os, time, random, string from uuid import uuid4 class Upload_File(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, related_name='user') def upload_pdf_validator(upload_pdf_obj): ext = os.path.splitext(upload_pdf_obj.name)[1] # [0] = returns path+filename valid_extension = ['.pdf'] if not ext in valid_extension: raise ValidationError(u'Unsupported file extension, .pdf only.') # New configuration for Auto rename field of `upload_pdf` # Refference --> https://code.djangoproject.com/ticket/22999 # Changes --> https://goo.gl/OSDcPk # # Example: # - input : This my uploaded file.pdf _qAYZtq9.pdf # - output: This-my-uploaded-file_x7szfe5_qAYZtq9.pdf # - `x7szfe5` is random string, it will making high scure. # - `qAYZtq9` is uuid4().hex @deconstructible class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): ext = filename.split('.')[-1] f_name = '-'.join(filename.replace('.pdf', '').split() ) rand_strings = ''.join( random.choice(string.lowercase+string.digits) for i in range(7) ) filename = '{}_{}{}.{}'.format(f_name, rand_strings, uuid4().hex, ext) return os.path.join(self.path, filename) # Please comment `validators=[upload_pdf_validator]` and `upload_to=` before migrate/makemigrations your database. # For more: https://docs.djangoproject.com/en/1.9/topics/migrations/#serializing-values upload_pdf = models.FileField( upload_to=PathAndRename('files/pdf/{}'.format(time.strftime("%Y/%m/%d"))), validators=[upload_pdf_validator] ) ### Update import os, time, uuid from django.db import models from django.utils.deconstruct import deconstructible class ImageUploader(models.Model): @deconstructible class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): # eg: filename = 'my uploaded file.jpg' ext = filename.split('.')[-1] #eg: 'jpg' uid = uuid.uuid4().hex[:10] #eg: '567ae32f97' # eg: 'my-uploaded-file' new_name = '-'.join(filename.replace('.%s' % ext, '').split()) # eg: 'my-uploaded-file_64c942aa64.jpg' renamed_filename = '%(new_name)s_%(uid)s.%(ext)s' % {'new_name': new_name, 'uid': uid, 'ext': ext} # eg: 'images/2017/01/29/my-uploaded-file_64c942aa64.jpg' return os.path.join(self.path, renamed_filename) image_path = time.strftime('images/%Y/%m/%d') image = models.ImageField(upload_to=PathAndRename(self.image_path))