Django - upload user uploaded images

I'm having problems servicing user uploaded files from a 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 are uploaded to the user_res / pictures / folder.

from settings.py project:

 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 like

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

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

 user_res/pictures/test.jpg 

The URL is dynamically generated using this line of code from the Django Picture model model:

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

I do not have dedicated url-s for static or media files in url.py file.

Does anyone have any ideas on how to get Django to serve multimedia files? I understand that for live environments I need to configure an HTTP server to serve this particular directory, but for now I want to support an easy development package.

Thanks.

+6
source share
2 answers

Edit the 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 settings.py projects to look like this:

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

Read the official Django documentation on how to upload files uploaded by the user. Link to documents: https://docs.djangoproject.com/en/1.5/howto/static-files/#serving-files-uploaded-by-a-user

+4
source

I think the url attribute returns a relative URL ( Django FileField documentation ), so you should have:

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

Relative URLs will not work because a user who visits "http: // localhost / books /" will request "http: //localhost/books/user_res/pictures/test.jpg".

0
source

All Articles