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
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
...
Check ImageField / FileField Django form Currently unable to trim the path to filename.