Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - serving user uploaded images

I am having some problems with serving user uploaded files from my Django application:

from models.py:

class Picture (models.Model):

    title = models.CharField(max_length=48)

    date_added = models.DateTimeField(auto_now=True)

    content = models.ImageField(upload_to='pictures')

From the Django admin the files get uploaded to the user_res/pictures/ folder.

from the project's settings.py:

MEDIA_ROOT = 'user_res'

MEDIA_URL = '/user_res/'

STATIC_ROOT = ''

STATIC_URL = '/static/'

Every time I try to reference a static resource (namely css or js files), everything works fine using URLs such as

http://localhost:8000/static/<subfolder>/main.css.

However, I cannot access user uploaded files (which get created by the admin interface in the user_res/pictures folder with a relative URL such as

user_res/pictures/test.jpg

the URL is dynamically created with this line of code from a Django Picture model callable:

return '<img src="{}"/>'.format(self.content.url)

I have no dedicated url-s for either static or media files in the url.py file.

Does anybody have any idea as to how to make Django serve the media files? I understand that for live environments I will need to configure an http server to serve that particular directory, but for now I want to maintain a lightweight development suite.

Thank you.

like image 396
Tudor Vintilescu Avatar asked Dec 16 '12 12:12

Tudor Vintilescu


1 Answers

Edit your urls.py file as shown below.

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

edit your projects settings.py to look like:

#Rest of the settings
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'
STATIC_ROOT = ''
STATIC_URL = '/static/'

Please read the official Django documentation about serving files uploaded by a user carefully. Link to docs: https://docs.djangoproject.com/en/1.5/howto/static-files/#serving-files-uploaded-by-a-user

like image 172
Jay Pee Avatar answered Sep 24 '22 11:09

Jay Pee