Login

CustomImageField for Django 1.0 alpha

Author:
hanksims
Posted:
August 7, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

The venerable CustomImageField, invented by Scott Barnham and rejiggered for newforms-admin by jamstooks.

This here is a stab at a post-Signals-refactor version. Seems to do 'er.

Note: This should be pointless once fs-refactor lands.

 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
from django.db.models import ImageField, FileField, signals
from django.conf import settings
from distutils.dir_util import mkpath
import shutil, os, glob, re

class CustomImageField(ImageField):
    """Allows model instance to specify upload_to dynamically.

    Model class should have a method like:

        def get_upload_to(self, attname):
            return 'path/to/%d' % self.id

    PLEASE NOTE:
        This should be pointless once fs-refactor lands.
        See the following page for updates:

         http://code.djangoproject.com/ticket/5361

    Based closely on: http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/
    Later updated for newforms-admin by jamstooks: http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/
    """
    def __init__(self, *args, **kwargs):
        if not 'upload_to' in kwargs:
            kwargs['upload_to'] = 'tmp'
        self.use_key = kwargs.get('use_key', False)
        if 'use_key' in kwargs:
            del(kwargs['use_key'])
        super(CustomImageField, self).__init__(*args, **kwargs)

    def contribute_to_class(self, cls, name):
        """Hook up events so we can access the instance."""
        super(CustomImageField, self).contribute_to_class(cls, name)
        signals.post_save.connect(self._move_image, sender=cls)

    def _move_image(self, instance=None, **kwargs):
        """
            Function to move the temporarily uploaded image to a more suitable directory
            using the model's get_upload_to() method.
        """
        if hasattr(instance, 'get_upload_to'):
            src = getattr(instance, self.attname)
            if src:
                m = re.match(r"%s/(.*)" % self.upload_to, src)
                if m:
                    if self.use_key:
                        dst = "%s%d_%s" % (
                          instance.get_upload_to(self.attname), 
                          instance.id, 
                          m.groups()[0]
                        )
                    else:
                        dst = "%s%s" % (
                          instance.get_upload_to(self.attname), 
                          m.groups()[0]
                        )
                    basedir = os.path.join(
                      settings.MEDIA_ROOT, 
                      os.path.dirname(dst)
                    )
                    fromdir = os.path.join(
                      settings.MEDIA_ROOT, 
                      src
                    )
                    mkpath(basedir)
                    shutil.move(fromdir, 
                      os.path.join(basedir, 
                                   m.groups()[0])
                    )
                    setattr(instance, self.attname, dst)
                    instance.save()

    def db_type(self):
        """Required by Django for ORM."""
        return 'varchar(200)'

More like this

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

Comments

KpoH (on August 8, 2008):

this

self.use_key = kwargs.get('use_key', False)
if 'use_key' in kwargs:
    del(kwargs['use_key'])

can be changed to

self.use_key = kwargs.pop('use_key', False)

#

ges (on June 22, 2009):

Exception Type: TypeError Exception Value: expected string or buffer Exception Location: C:\Python25\lib\re.py in match, line 137 D:\django_projects\ges..\ges\CustomImageField.py in _move_image m = re.match(r'%s/(.*)' % self.upload_to, src)

#

Please login first before commenting.