<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
		>
<channel>
	<title>Comments on: Uploading images to a dynamic path with Django</title>
	<atom:link href="http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/feed/" rel="self" type="application/rss+xml" />
	<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/</link>
	<description>Code and comments on web development, Django, Python and things (un)related.</description>
	<lastBuildDate>Tue, 13 Jul 2010 16:31:27 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<item>
		<title>By: Scott</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-776</link>
		<dc:creator>Scott</dc:creator>
		<pubDate>Thu, 04 Mar 2010 16:35:08 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-776</guid>
		<description>Thanks Mishu, but there&#039;s a newer official way to do this in Django.

See:
http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/</description>
		<content:encoded><![CDATA[<p>Thanks Mishu, but there&#8217;s a newer official way to do this in Django.</p>
<p>See:<br />
<a href="http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/" rel="nofollow">http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/</a></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Mishu</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-775</link>
		<dc:creator>Mishu</dc:creator>
		<pubDate>Wed, 03 Mar 2010 12:25:23 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-775</guid>
		<description>Here is the updated version that works with latest Django:
&lt;pre&gt;
from django.db.models import ImageField, signals


class CustomImageField(ImageField):
    &quot;&quot;&quot;Allows model instance to specify upload_to dynamically.

    Model class should have a method like:

        def get_upload_to(self, attname):
            return &#039;path/to/%d&#039; % self.id

    Based on: http://code.djangoproject.com/wiki/CustomUploadAndFilters
    &quot;&quot;&quot;
    def __init__(self, *args, **kwargs):
        if not &#039;upload_to&#039; in kwargs:
            kwargs[&#039;upload_to&#039;] = &#039;dummy&#039;
        self.prime_upload = kwargs.get(&#039;prime_upload&#039;, False)
        if &#039;prime_upload&#039; in kwargs:
            del(kwargs[&#039;prime_upload&#039;])
        super(CustomImageField, self).__init__(*args, **kwargs)

    def contribute_to_class(self, cls, name, **kwargs): 
        &quot;&quot;&quot;Hook up events so we can access the instance.&quot;&quot;&quot;
        super(CustomImageField, self).contribute_to_class(cls, name)
        if self.prime_upload:
            signals.post_init.connect(self._get_upload_to, sender=cls)
        signals.pre_save.connect(self._get_upload_to, sender=cls)

    def _get_upload_to(self, instance=None, **kwargs):
        &quot;&quot;&quot;Get dynamic upload_to value from the model instance.&quot;&quot;&quot;
        if hasattr(instance, &#039;get_upload_to&#039;):
            self.upload_to = instance.get_upload_to(self.attname)

    def db_type(self):
        &quot;&quot;&quot;Required by Django for ORM.&quot;&quot;&quot;
        return &#039;varchar(100)&#039;
&lt;/pre&gt;</description>
		<content:encoded><![CDATA[<p>Here is the updated version that works with latest Django:</p>
<pre>
from django.db.models import ImageField, signals

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

    Based on: <a href="http://code.djangoproject.com/wiki/CustomUploadAndFilters" rel="nofollow">http://code.djangoproject.com/wiki/CustomUploadAndFilters</a>
    """
    def __init__(self, *args, **kwargs):
        if not 'upload_to' in kwargs:
            kwargs['upload_to'] = 'dummy'
        self.prime_upload = kwargs.get('prime_upload', False)
        if 'prime_upload' in kwargs:
            del(kwargs['prime_upload'])
        super(CustomImageField, self).__init__(*args, **kwargs)

    def contribute_to_class(self, cls, name, **kwargs):
        """Hook up events so we can access the instance."""
        super(CustomImageField, self).contribute_to_class(cls, name)
        if self.prime_upload:
            signals.post_init.connect(self._get_upload_to, sender=cls)
        signals.pre_save.connect(self._get_upload_to, sender=cls)

    def _get_upload_to(self, instance=None, **kwargs):
        """Get dynamic upload_to value from the model instance."""
        if hasattr(instance, 'get_upload_to'):
            self.upload_to = instance.get_upload_to(self.attname)

    def db_type(self):
        """Required by Django for ORM."""
        return 'varchar(100)'
</pre>
]]></content:encoded>
	</item>
	<item>
		<title>By: Scott</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-301</link>
		<dc:creator>Scott</dc:creator>
		<pubDate>Mon, 25 Aug 2008 21:48:30 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-301</guid>
		<description>@Fidel Ramos

I have a new short post with an example of how to get dynamic upload paths since the FileStorageRefactor merge.  It uses a callable in the upload_to parameter and is much simpler than the method in this post.

See:
&lt;a href=&quot;http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/&quot; rel=&quot;nofollow&quot;&gt;Dynamic upload paths in Django&lt;/a&gt;</description>
		<content:encoded><![CDATA[<p>@Fidel Ramos</p>
<p>I have a new short post with an example of how to get dynamic upload paths since the FileStorageRefactor merge.  It uses a callable in the upload_to parameter and is much simpler than the method in this post.</p>
<p>See:<br />
<a href="http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/" rel="nofollow">Dynamic upload paths in Django</a></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Fidel Ramos</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-292</link>
		<dc:creator>Fidel Ramos</dc:creator>
		<pubDate>Thu, 21 Aug 2008 11:23:02 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-292</guid>
		<description>This solution was working fine until the File Storage refactoring (http://code.djangoproject.com/wiki/FileStorageRefactor), and I&#039;m afraid the changes to make it work again may be extensive. Anyone knows a File Storage-compatible substitute?</description>
		<content:encoded><![CDATA[<p>This solution was working fine until the File Storage refactoring (<a href="http://code.djangoproject.com/wiki/FileStorageRefactor" rel="nofollow">http://code.djangoproject.com/wiki/FileStorageRefactor</a>), and I&#8217;m afraid the changes to make it work again may be extensive. Anyone knows a File Storage-compatible substitute?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: mat</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-288</link>
		<dc:creator>mat</dc:creator>
		<pubDate>Fri, 08 Aug 2008 10:04:19 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-288</guid>
		<description>Because of http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Signalrefactoring I guess this is gonna look like this:

	def contribute_to_class(self, cls, name):
		&quot;&quot;&quot;
		Hook up events so we can access the instance.
		&quot;&quot;&quot;
		super(CustomImageField, self).contribute_to_class(cls, name)
		if self.prime_upload:
			signals.post_init.connect(self._get_upload_to, sender=cls)
		signals.pre_save.connect(self._get_upload_to, sender=cls)

	def _get_upload_to(self, **kwargs):
		&quot;&quot;&quot;
		Get dynamic upload_to value from the model instance.
		&quot;&quot;&quot;
		instance = kwargs[&#039;instance&#039;]
		if hasattr(instance, &#039;get_upload_to&#039;):
			self.upload_to = instance.get_upload_to(self.attname)</description>
		<content:encoded><![CDATA[<p>Because of <a href="http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Signalrefactoring" rel="nofollow">http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Signalrefactoring</a> I guess this is gonna look like this:</p>
<p>	def contribute_to_class(self, cls, name):<br />
		&#8220;&#8221;"<br />
		Hook up events so we can access the instance.<br />
		&#8220;&#8221;"<br />
		super(CustomImageField, self).contribute_to_class(cls, name)<br />
		if self.prime_upload:<br />
			signals.post_init.connect(self._get_upload_to, sender=cls)<br />
		signals.pre_save.connect(self._get_upload_to, sender=cls)</p>
<p>	def _get_upload_to(self, **kwargs):<br />
		&#8220;&#8221;"<br />
		Get dynamic upload_to value from the model instance.<br />
		&#8220;&#8221;"<br />
		instance = kwargs['instance']<br />
		if hasattr(instance, &#8216;get_upload_to&#8217;):<br />
			self.upload_to = instance.get_upload_to(self.attname)</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Ben</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-287</link>
		<dc:creator>Ben</dc:creator>
		<pubDate>Wed, 06 Aug 2008 04:02:12 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-287</guid>
		<description>In an effort to get this going with newforms-admin I tried working with the &lt;code&gt;post_save&lt;/code&gt; signal.  I&#039;ve posted it on my blog:
http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/</description>
		<content:encoded><![CDATA[<p>In an effort to get this going with newforms-admin I tried working with the <code>post_save</code> signal.  I&#8217;ve posted it on my blog:<br />
<a href="http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/" rel="nofollow">http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/</a></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Ben</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-284</link>
		<dc:creator>Ben</dc:creator>
		<pubDate>Tue, 05 Aug 2008 02:38:45 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-284</guid>
		<description>Great Post! I&#039;ve used this for a while now.
However, this seems to have broken with the inclusion of the Newforms Admin now. I&#039;m getting a DoesNotExist error on the instance. Have you tried the newest revision?</description>
		<content:encoded><![CDATA[<p>Great Post! I&#8217;ve used this for a while now.<br />
However, this seems to have broken with the inclusion of the Newforms Admin now. I&#8217;m getting a DoesNotExist error on the instance. Have you tried the newest revision?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Scott</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-205</link>
		<dc:creator>Scott</dc:creator>
		<pubDate>Tue, 20 May 2008 12:02:51 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-205</guid>
		<description>@Michael

I&#039;ve just posted an updated version (see above) which should work in this situation.</description>
		<content:encoded><![CDATA[<p>@Michael</p>
<p>I&#8217;ve just posted an updated version (see above) which should work in this situation.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Michael</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-204</link>
		<dc:creator>Michael</dc:creator>
		<pubDate>Tue, 20 May 2008 04:55:40 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-204</guid>
		<description>The CustomImageField class doesn&#039;t properly save the image to the specified dynamic path via the following code:

        if form.is_valid():
            l = ListingImage()

            uploadedImage = form.cleaned_data[&#039;image&#039;]   # an UploadedFile object
            l.save_image_file(uploadedImage.filename, uploadedImage.content)

            l.caption = form.cleaned_data[&#039;caption&#039;]
            l.sort = form.cleaned_data[&#039;sort&#039;]
            l.save()
            

ListingImage.image is a CustomImageField()

Anyone know why calling save_image_file() doesn&#039;t invoke the get_upload_to() to save the image to the dynamic path?</description>
		<content:encoded><![CDATA[<p>The CustomImageField class doesn&#8217;t properly save the image to the specified dynamic path via the following code:</p>
<p>        if form.is_valid():<br />
            l = ListingImage()</p>
<p>            uploadedImage = form.cleaned_data['image']   # an UploadedFile object<br />
            l.save_image_file(uploadedImage.filename, uploadedImage.content)</p>
<p>            l.caption = form.cleaned_data['caption']<br />
            l.sort = form.cleaned_data['sort']<br />
            l.save()</p>
<p>ListingImage.image is a CustomImageField()</p>
<p>Anyone know why calling save_image_file() doesn&#8217;t invoke the get_upload_to() to save the image to the dynamic path?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Scott</title>
		<link>http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/comment-page-1/#comment-199</link>
		<dc:creator>Scott</dc:creator>
		<pubDate>Fri, 02 May 2008 07:40:06 +0000</pubDate>
		<guid isPermaLink="false">http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/#comment-199</guid>
		<description>Hi Chris.

Yes, you can.  The model that contains the &lt;code&gt;CustomImageField&lt;/code&gt; gets to build up the path.  Assuming you have a &lt;code&gt;Photo&lt;/code&gt; model which has a &lt;code&gt;CustomImageField&lt;/code&gt; and is related to a user, you could do something like:

&lt;pre&gt;class Photo(models.Model):
    user = models.ForeignKey(User, related_name=&#039;photos&#039;)
    image = CustomImageField(upload_to=&#039;photos&#039;)
    creation_date = models.DateTimeField()
    ...
    
    def get_upload_to(self, field_attname):
        return self.user.username
&lt;/pre&gt;

The upload path will be made up of the media path, username and filename.  Assuming the username is &quot;ted&quot;, you will get something like: &lt;code&gt;/path/to/media/ted/head.jpg&lt;/code&gt;</description>
		<content:encoded><![CDATA[<p>Hi Chris.</p>
<p>Yes, you can.  The model that contains the <code>CustomImageField</code> gets to build up the path.  Assuming you have a <code>Photo</code> model which has a <code>CustomImageField</code> and is related to a user, you could do something like:</p>
<pre>class Photo(models.Model):
    user = models.ForeignKey(User, related_name='photos')
    image = CustomImageField(upload_to='photos')
    creation_date = models.DateTimeField()
    ...

    def get_upload_to(self, field_attname):
        return self.user.username
</pre>
<p>The upload path will be made up of the media path, username and filename.  Assuming the username is &#8220;ted&#8221;, you will get something like: <code>/path/to/media/ted/head.jpg</code></p>
]]></content:encoded>
	</item>
</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.228 seconds -->
