Search code examples
djangouploadimagefield

django imagefield upload_to does not work at all


I've written a simple django app to test ImageField, but I'm running into problem where upload_to just doesn't seem to work. Below is the code:

  1 from django.db import models
  2 
  3 # Create your models here.
  4 class TestImage(models.Model):
  5     img = models.ImageField(max_length=256, upload_to='images')

In my settings.py I have:

  2 from os.path import dirname, join, abspath
  3 __dir__ = dirname(abspath(__file__))
 50 MEDIA_ROOT = join(__dir__, 'static')
 55 MEDIA_URL = '/media/'

Then I start python shell using manage.py:

jchin@ubuntu:~/workspace/testimage$ ./manage.py shell
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import settings
>>> from image_app.models import TestImage
>>> p = TestImage(img='test.jpg')
>>> p.save()
>>> p.img.name
'test.jpg'
>>> p.img.path
u'/home/jchin/workspace/testimage/static/test.jpg'
>>> p.img.url
'/media/test.jpg'

As you can see from the result, django totally ignored my 'upload_to' paramater. Which I can't figure out why. From the documentation I should be expecting p.img.path to return "/home/jchin/workspace/testimage/static/images/test.jpg" and in the DB storing "images/test.jpg", correct? But the DB simply store the file name only:

mysql> select * from image_app_testimage;
+----+-----------+
| id | img       |
+----+-----------+
|  1 | test.jpg  |
+----+-----------+
1 rows in set (0.00 sec)

I checked all the documentations and I could not find what I am doing wrong. Anyone have any ideas? I'm using django 1.2.5 and it should support upload_to.

Please help! John


Solution

  • But upload_to is for uploading, as the name implies. You're not uploading, you're assigning an image directly. It's only when you create a FileField object -by uploading from a form, for example- that upload_to is used.