this is a followup to my question here: ImageField / FileField Django form Currently unable to trim the path to filename
In my Django app, there is an imagefield uploaded to S3 After trim the imagefile path name, the image is not accessible because the url is trimmed. How can i trim the display but dont trim the path ?
I manage to trim the display showing the filename like this
class CustomClearableFileInput(ClearableFileInput):
def get_context(self, name, value, attrs):
logging.debug("%s",name)
logging.debug("%s",value)
value.name = path.basename(value.name)
context = super().get_context(name, value, attrs)
return context
class CompanySettingEdit(forms.ModelForm):
company_logo = forms.ImageField(widget=CustomClearableFileInput)
this is the output:
https://imgur.com/a/M42Mz <-- display correct
https://bucketname.s3.amazonaws.com/media/certiport_logo.png <-- invalid url
If I dont trim it:
class CustomClearableFileInput(ClearableFileInput):
def get_context(self, name, value, attrs):
logging.debug("%s",name)
logging.debug("%s",value)
# value.name = path.basename(value.name) <-- remove this
context = super().get_context(name, value, attrs)
return context
class CompanySettingEdit(forms.ModelForm):
company_logo = forms.ImageField(widget=CustomClearableFileInput)
this is the output:
https://imgur.com/a/rGi8f <-- display incorrect
https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png <--valid url
my goal is to:
display: certiport_logo.png
url: https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png
How can I achieve this ?
The
url
property of a FileField/ImageField is dynamic: it depends on thename
attribute just asstr()
does at the time it is called. Instead, let's write to something besidesname
and change the template to use it instead:And for the template (modified and pretty printed from django source)
In your case I suggest JSONField instead of ImageField. On that way you in your can have:
class example: