How do I set an initial value for a FileField that will display in a ClearableFileInput widget when creating a new object (unbound form)?
I have tried the following but widget.value does not return a FeildFile instance if it is the first time the user is creating the object:
models.py
class MyModel(models.Model):
myfile=models.FileField()
forms.py
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfile'].initial= 'myfile.pdf'
class Meta:
model = Issuer
fields = ['myfile']
This results in :
Similarly, setting a default value in the modelfield does not work:
class MyModel(models.Model):
myfile=models.FileField(default='myfile.pdf')
The widget initial value is still None, but if it is left empty and saved the file object myfile.pdf will be created. The settings.MEDIA_URL and urls.py is definitely correct and the file is on the system because it is loaded after form save.
What I am missing is showing it as an initial value before a form is saved and an object created.
This answer suggests you can't provide initial data but you can provide an initial value with a url attribute to fake the appearance of a file. It's not clear how you would do this though.
Trying to create an initial file object in the form also returns widget.value = None
class MyForm(forms.ModelForm):
f_path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL, 'myfile.pdf')
f = open(f_path)
myfile = File(f)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['privacy_policy'].initial = self.myfile
