Search code examples
djangodjango-viewsdjango-urlsdjango-uploads

How to add a file from a filefield in Django to urls and views?


I'm doing a Django project, and I have a model called Projects, in this model I have a FileField inwhich files get uploaded to /media/files/YEAR/MONTH/DATE/.

settings.py:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

models.py:

class Project(models.Model):
    ...
    file_upload = models.FileField(upload_to='files/%Y/%m/%d', max_length=100, null=True, blank=True, default='')

template:

...
{% if project.file_upload %}
<tr>
  <td>File</td>
  <td><a href="{{ project.file_upload.url }}">{{ project.file_upload.name }} (Size: {{ project.file_upload.size|filesizeformat }})</a></td>
</tr>
{% endif %}
...

Now a link to a file would be something like: /media/files/2016/05/25/picture.png or /media/files/2016/05/25/report.pdf

Currently I get a 404 page not found, whenever I click the link. That is ofcourse because the path is not in the urls.py, but since you usually add a view to an url, I don't know how you would do it with a single file, as it would seem to me a view wouldn't be necessary.

How do I tell Django in urls (And possibly in views) how to get that file? I want to be able to click the link and then either view the picture/pdf in the browser or simply download the file.


Solution

  • Django does not serve static files. To force these files to be served when DEBUG=True, add this code to urls.py:

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    (from https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-static-files-during-development)

    You do not need to tell Django about static files in views.py