-->

ImageField / FileField Django form Currently unabl

2019-02-28 06:00发布

问题:

I have a ImageField that stores in AWS S3 (similar to FileField). In the form, it has this "Currently" label that shows the image file path. I would like to trim and just show the filename.

referring to the latest answer in Django : customizing FileField value while editing a model, I still cant get it to work.

It shows "Currently" with the file path name like this: https://imgur.com/a/xkUZi

form.py

class CustomClearableFileInput(ClearableFileInput):
    def get_template_substitution_values(self, value):
        """
        Return value-related substitutions.
        """
        logging.debug("CustomClearableFileInput %s",value) <-- it never came here
        return {
            'initial': conditional_escape(path.basename(value.name)),
            'initial_url': conditional_escape(value.url),
        }

class CompanySettingEdit(forms.ModelForm):
    display_companyname = forms.CharField(max_length=50, required=True)    
    company_logo = forms.ImageField(widget=CustomClearableFileInput)

    class Meta:
        model = Company
        fields = ("display_companyname","company_logo")

model.py

class Company(models.Model):
    display_companyname = models.CharField(max_length=50)    
    company_logo = models.ImageField(upload_to=upload_to('company_logo/'), blank=True, null=True, storage=MediaStorage())

How can I have something like this: Currently: filename.jpg

FYI - ImageField / FileField, I tried both it doesnt make a difference. Im using Django==1.11.7

回答1:

In Django 1.11.x get_template_substitution_values is deprecated. New implementation of CustomClearableFileInput could be as follow:

class CustomClearableFileInput(ClearableFileInput):
    def get_context(self, name, value, attrs):
        value.name = path.basename(value.name)
        context = super().get_context(name, value, attrs)       
        return context