Login

ImageField with per user folder

Author:
pigletto
Posted:
January 1, 2008
Language:
Python
Version:
.96
Tags:
imagefield path
Score:
3 (after 3 ratings)

If you need to upload Image files into folders qualified with user name eg.: 'images/user1/2008/01/01' then you may use this snippet.

In order to use it you have to install ThreadLocals middleware as described here: http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser

Then just import UserImageField class at your models.py and specify 'upload_to' parameter with '%(user)s' in the path eg.:

image3 = UserImageField(_('Image 3'), upload_to='flower_images/%(user)s/%Y/%m/%d', null=True, blank=True)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# to use this you need to install ThreadLocals Middleware from 
# http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
#
# then change import path below in <...>
from django.db import models
from <ThreadLocals middleware path here> import get_current_user

class UserImageField(models.ImageField):
    def get_internal_type(self):
        return 'ImageField'

    def get_directory_name(self):
        user = get_current_user()
        upl_to = self.upload_to.replace('%(user)s', '%%(user)s')
        upl_to = datetime.datetime.now().strftime(upl_to)
        upl_to = upl_to % {'user':user}
        return os.path.normpath(force_unicode(upl_to))

More like this

  1. Updated FileField / ImageField with a delete checkbox by tomZ 7 years, 2 months ago
  2. FileField / ImageField with a delete checkbox by tomZ 7 years, 6 months ago
  3. slug filename by willhardy 5 years, 10 months ago
  4. Easy file upload handler by mattdw 6 years, 8 months ago
  5. UPDATED: Django Image Thumbnail Filter by danfairs 7 years, 7 months ago

Comments

pigletto (on January 1, 2008):

Added:

def get_internal_type(self): return 'ImageField'

#

Please login first before commenting.