About Checking the Existence of a Linked File

Check the existence of the linked file using its storage attribute:

1
2
3
4
def get_avatar_url(user):
    if user.avatar and user.avatar.storage.exists(user.avatar.name):
        return user.avatar.url
    return ""

This works with files saved in the file system, on AWS S3, or elsewhere.

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Django 1.11 Amazon Web Services