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 view form. Let me explain.
models.py:
class DemoVar_model(models.Model):
...
Welcome_sound=models.FileField(upload_to='files/%Y/%m/%d')
forms.py:
class DemoVar_addform(ModelForm):
...
class Meta:
model = DemoVar_model
views.py:
soundform = DemoVar_addform(instance=ivrobj)
....
return render_to_response(template,{'soundform':soundform}, ....)
Now I want to edit this model in my view. When I look in browser, I see the form being displayed as
Welcome sound: Currently: welcome_files/2011/04/27/15_35_58_ojCompany.wav.mp3
Change : <Choose File button>
I want to change this "Currently" value, which describes the whole path of the file as it exits on my server. I want to trim this string to just the filename without the path. How do I accomplish that?
If you want an easier way and avoid to rewrite the render logic of the widget, you can do a little hack.
And then manually set the widget for the field.
You need to override the ClearableFileInput that is currently used, to change the way it's displayed.
Here is the code of the new
ShortNameFileInput
which inherit from the defaultClearableFileInput
with just a change on the 19th line to only show the file name:To use it in your form, you'll have to manually set the widget you want to use :
That should do the trick.
One way of doing it, would be to write a custom form widget and override the render method.
Django 1.10.x or older version
The easiest way is to override the
template_substitution_values
in defaultClearableFileInput
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.then use the widget in forms.py as follow:
Django 1.11.x or later versions
Check ImageField / FileField Django form Currently unable to trim the path to filename.