Django : customizing FileField value while editing a model

前端 未结 4 1276
孤城傲影
孤城傲影 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条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 13:37

    Django 1.10.x or older version


    The easiest way is to override the template_substitution_values in default ClearableFileInput django widget that will be used later in rendering the form. This is a much cleaner approach that does not result in any unnecessary code duplication.

    from os import path
    from django.forms.widgets import ClearableFileInput
    from django.utils.html import conditional_escape
    
    class CustomClearableFileInput(ClearableFileInput):
        def get_template_substitution_values(self, value):
            """
            Return value-related substitutions.
            """
            return {
                'initial': conditional_escape(path.basename(value.name)),
                'initial_url': conditional_escape(value.url),
            }
    

    then use the widget in forms.py as follow:

    class DemoVar_addform(ModelForm):
        Welcome_sound = forms.FileField(widget=CustomClearableFileInput)    
        ...
    
        class Meta:
            model = DemoVar_model
    
        ...
    

    Django 1.11.x or later versions


    Check ImageField / FileField Django form Currently unable to trim the path to filename.

提交回复
热议问题