Login

Auto rename file upload with file validator

Author:
agusmakmun
Posted:
May 1, 2016
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

This script tested under Django==1.9.*

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.