Thursday, March 21, 2013

django ImageField ignores upload_to kwarg

I've fallen into a problem with resolving the correct url of uploaded images. I've made sure that my routing/templates work correctly and the problem is somewhere inside the model layer.

This is my model class:

from django.db import models
from tinymce.models import HTMLField

class Article(models.Model):
    """News article, displayed on homepage to attract users"""
    class Meta:
        db_table = 'article'
    title = models.CharField(max_length=64)
    headline = models.CharField(max_length=255)
    content = HTMLField()
    image = models.ImageField(upload_to = 'articles', null=True, blank=True)
    active = models.BooleanField()
    created_at = models.DateTimeField()
    def __unicode__(self):
        return self.title

Now when I open my django shell, I get wrong url/path values. The 'upload_to' kwarg (defined in Article model for image field) is ignored and I don't know why.

$ ./manage.py shell
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from articles.models import Article
>>> Article.objects.all().get(pk=1)
<Article: Blackened Recordings Launches>
>>> Article.objects.all().get(pk=1).image.path
u'/var/www/django/djninja/djninja/media/slide-03.jpg'
>>> Article.objects.all().get(pk=1).image.url
'/media/slide-03.jpg'

I've defined MEDIA and MEDIA_ROOT in the settings.py:

PROJECT_DIR = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")
MEDIA_URL = '/media/'

I expect the path/url to be media/articles/slide.jpg instead of media/slide.jpg

Thank you in advance for any suggestions!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment