Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - forms.FileField() initial value

Is it possible to give initial value for forms.FileField() dynamically?

like image 567
Sivasubramaniam Arunachalam Avatar asked Dec 05 '10 10:12

Sivasubramaniam Arunachalam


People also ask

What is initial in Django forms?

initial is used to change the value of the field in the input tag when rendering this Field in an unbound Form. initial accepts as input a string which is new value of field. The default initial for a Field is empty. Let's check how to use initial in a field using a project.

How do you make a field optional in Django?

If you want to allow blank values in a date field (e.g., DateField , TimeField , DateTimeField ) or numeric field (e.g., IntegerField , DecimalField , FloatField ), you'll need to use both null=True and blank=True . Save this answer. Show activity on this post. Use null=True and blank=True in your model.

How do you make a field not required in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).


2 Answers

I'm not sure, if this is what you want, but…

Obviously you cannot set initial data for a file input (this would imply that you send a file to the user). Django has a ClearableFileInput widget though, and this widget pretends to show initial data: it displays a link to the uploaded file if the link is present.

This is implemented through checking if the initial object (the object passed to form constructor in files dictionary) has the url attribute. Once you set this attribute, the widget will display the "Currently link" line.

By the way, if you got the file object using a File Storage, then you can get the link to that file using storage's url() method.

like image 53
grisumbras Avatar answered Sep 28 '22 19:09

grisumbras


By security standards, <input type="file"> can't have a default value and it can't be manipulated.

The reason is, that a hacker can set the default value of the file input to any important file on your system (containing passwords, certificates and so on), hide this field using CSS and you will never know that you have uploaded something to hackers host.

like image 37
Silver Light Avatar answered Sep 28 '22 20:09

Silver Light