Login

ImageField with per user folder

Author:
pigletto
Posted:
January 1, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

pigletto (on January 1, 2008):

Added:

def get_internal_type(self): return 'ImageField'

#

Please login first before commenting.