Django : customizing FileField value while editing a model

前端 未结 4 1277
孤城傲影
孤城傲影 2021-02-04 13:27

I\'ve got a model, with FileField. When I edit this model in a view, I want to change the \"current\" value of FileField which gets displayed in the vi

4条回答
  •  梦毁少年i
    2021-02-04 13:43

    If you want an easier way and avoid to rewrite the render logic of the widget, you can do a little hack.

    from os import path
    from django import forms
    
    
    class FormatString(str):
    
        def format(self, *args, **kwargs):
            arguments = list(args)
            arguments[1] = path.basename(arguments[1])
            return super(FormatString, self).format(*arguments, **kwargs)
    
    
     class ClearableFileInput(forms.ClearableFileInput):
    
         url_markup_template = FormatString('{1}')
    

    And then manually set the widget for the field.

    class DemoVar_addform(ModelForm):
    
        class Meta:
            model = DemoVar_model
            widgets = {
                'Welcome_sound': ClearableFileInput,
            }   
    

提交回复
热议问题