Opened 5 years ago

Closed 5 years ago

#31725 closed New feature (wontfix)

Setting ImageField and FileField default to a static file

Reported by: Daniel González Fernández Owned by: nobody
Component: Database layer (models, ORM) Version: 3.0
Severity: Normal Keywords: static image default
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I think that the user who made this comment (https://code.djangoproject.com/ticket/25905#comment:8) makes a valid point.

This is an important issue because currently, it doesn't allow to serve as default an static file (this is useful for example when setting a default avatar image in a user models, and in many others use's cases, as it allow to have many objects referencing the same file, instead of each one of them having a copy)

In development, where is a common practice to have the media and static folders in the root of the project, this is easily solved by doing:

avatar = ImageField(default="../static/default_avatar.png", blank=True).

But what about production, when you usually serve your static files from a CND or solucions like AWS S3 ???

The best solution I've come up with so far is to allow that field to be null, and explicitly right the get method of that field:

avatar = ImageField(blank=True, null=true)

def get_avatar(self):
    # variable PATH_TO_DEFAULT_STATIC_IMAGE depends on the enviroment
    # on development, it would be something like "localhost:8000/static/default_avatar.png"
    # on production, it would be something like "https://BUCKET_NAME.s3.amazonaws.com/static/default_avatar.png"
    return self.avatar if self.avatar else <PATH_TO_DEFAULT_STATIC_IMAGE>

However, it does look a little bit over-engineer, considering that most of the time, the default is an static file.

Change History (2)

comment:1 by Alexandr Tatarinov, 5 years ago

I am not sure this should be solved on the model level, because IMHO it is related to the presentation level, so I would suggest solving this on Form/Template level.
When using i.e. DRF I would place get_avatar in the serializer and use SerializerMethodField. Also, I believe this can be solved on an individual codebase level without the need to integrate into Django.
So basically, I would suggest leaving the field empty and handle the default image somewhere else. I may be missing some context, though.

Last edited 5 years ago by Alexandr Tatarinov (previous) (diff)

comment:2 by Carlton Gibson, 5 years ago

Resolution: wontfix
Status: newclosed

Yes, I think if there's no image then setting null=True is correct. You could use a custom field to encapsulate the placeholder handling but it strikes me doing it at the presentation layer is fine.

Note: See TracTickets for help on using tickets.
Back to Top