Search code examples
djangodjango-media

How to download files from user_directory_path in django


I am trying to download files that were uploaded to my django media directory. I am able to upload the files successfully, but I don't know the best method of downloading back these files. I have seen different examples online but I don't fully understand them. Here are my codes

models.py:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class Profile(models.Model):
       user = models.OneToOneField(User, on_delete=models.CASCADE)
       certification = models.FileField(upload_to=user_directory_path, blank=True)

urls.py

    urlpatterns = [
    .........
    path('profile/', user_views.profile, name='profile'),

]

if settings.DEBUG:
   urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

file.html:

        <a href="{{ user.profile.certification.url }}">Download Certification</a>

I get this error:

ValueError
     The 'certification' attribute has no file associated with it.

Do I create a view in my views.py and a url in my urls.py to handle the download? If so How do I go about it.


Solution

  • The error message is quite clear:

    The 'certification' attribute has no file associated with it.

    which means that this profile instance's certification field is empty (no file has been uploaded). And you can't build an url without the file path, do you ?

    You have two solutions here: either make the certification field required (remove the blank=True argument) - but this won't solve the issue if you already have profiles without certifications -, and / or test the profile.certification before trying to get the url:

    {% if user.profile.certification %}
       <a href="{{ user.profile.certification.url }}">Download Certification</a>  
    {% else %}
        <p>This user hasn't uploaded their certification</p>
    {% endif %}