0

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.

Bruce
  • 103
  • 1
  • 8

1 Answers1

0

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 %}
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Thanks. I cleared my db an re-uploaded the files and the {{ user.profile.certification.url }} worked. I had the profile created without the certifications. Thanks again – Bruce Oct 09 '19 at 11:56
  • @Bruce glad it solved your problem (you may consider accepting the answer then). Note that you should still test whether the certification file exists before displaying the url in your template. – bruno desthuilliers Oct 09 '19 at 13:52
  • Yes I did that. Thanks – Bruce Oct 10 '19 at 09:21