django set media path to default image in model

1.7k views Asked by At

My project structure:

MyProject/
    App1/
    App2/
    MyProject/
    Static/
        uploads/
            image.jpeg/

In my settings I have:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, '/static/uploads/')

I want to set image.jpeg as default profile picture

My model:

def get_upload_file_name(instance, filename):
    return "uploads/{}_{}".format(str(time()).replace('.','_'), filename)

class User(AbstractBaseUser, PermissionsMixin):
    thumbnail = models.FileField(upload_to=get_upload_file_name, default="image.jpeg")

Here I have written a method get_upload_file_name so that there wont be any error on duplicate filename. When user change their profile picture I want the image to be saved on the same directory.

Need help ....

1

There are 1 answers

0
Chris Hawkes On

What you should probably do is use Python to create a new username directory for each profile picture that gets uploaded. That way if they upload multiple's, each one overwrites the last.

As far as displaying a default image I would say you should do that in your template.

{% if username.image == "" %}http://www.yoursite.com/your_image.jpeg{% else %} username.image {% endif %}

Another method is to use Javascript to detect image not found and display a default.

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />