0

I have some model with a FileField() looks like this:

image = models.FileField(upload_to='/Users/john/projects/MyDjangoApp/foobars/images/')

So foobar is some module from MyDjangoApp. In future there comes another module like barfoos and this will have an own images folder.

What I don't understand is how to handle this in the template. Now there stand something like:

<td><img src="{{ foobar.image.url }}" height="350" width="350"></td>

So there stand the following:

/Users/john/projects/MyDjangoApp/foobars/images/71RkbKwBxnL._SL1004_.jpg

But it must be, something like:

http://127.0.0.1:8000/foobars/images/71RkbKwBxnL._SL1004_.jpg

All url patterns I find only handle this if the images hosted in /MyDjangoApp/static/images, I wish to handle the files in /MyDjangoApp/foobars/images and later /MyDjangoApp/barfoos/images.

Ho to handle this in Django.

Thanks a lot for your time!

user1644033
  • 277
  • 5
  • 17

1 Answers1

2

The upload_to argument should be a path relative to your MEDIA_ROOT setting. The url that you'll use to access the file is the same relative path appended to your MEDIA_URL setting.

Also check out the documentation on FileFields and ImageFields and on the MEDIA_ROOT and MEDIA_URL settings

knbk
  • 52,111
  • 9
  • 124
  • 122
  • Thats right, but I will multi MEDIA_ROOT and on this multi MEDIA_URL settings, how can I implement this. Both of my "packeges" have own MEDIA_ROOT paths, thats why in the model upload_to is an absolute path. – user1644033 Jul 28 '13 at 11:57
  • Now I have the following in the settings: MEDIA_URL = 'http://127.0.0.1:8000/' and MEDIA_ROOT = '/Users/john/projects/MyDjangoApp/' in the model: image = models.ImageField(upload_to='foobars/images') the file url i get: http://127.0.0.1:8000/foobars/images/71bYTz3ti6L._SL1200_.jpg BUT 404 But the images still there upload works fine... Thanks for every help! – user1644033 Jul 28 '13 at 12:19
  • 1
    Check out [this question](http://stackoverflow.com/questions/5517950/django-media-url-and-media-root) for help with your 404 error. In general it's better to use a relative url, so `MEDIA_URL = '127.0.0.1:8000/'` becomes `MEDIA_URL = '/'`. – knbk Jul 28 '13 at 12:34