2

I want to create a flask_wtf form with a FileField, but I want the file input to be default. How can I achieve this? Eg:

class InvoiceForm(FlaskForm):
    a = StringField()

For this form, I can create directly as : form = InvoiceForm(a='123')

For a similar case:

class InvoiceForm(FlaskForm):
    a = FileField()

I want to call the form with the default filefield. How can I achieve this ?

Dipesh
  • 31
  • 1
  • 6

1 Answers1

2

Using the file path of the default file, open the file (given its extension) and assign the file object to the form data.

For example, if your form FileField is for images (such as .png, .jpg) then you can create the form field as you normally would:

from flask_wtf.file import FileField, FileAllowed   

class InvoiceForm(Form):
  a = FileField(validators=[FileAllowed(['jpg', 'png'])])

Then in your route, you can open the image object from the given file path (note I would advise not hardcoding the file path, but rather store it as an environment variable) and store the image object to the form.a.data:

from PIL import Image  # Used for opening image objects

@example.route('/', methods=['GET', 'POST']
def example():

  form = InvoiceForm()
  form.a.data = Image.open(default_file_path)
  # rest of route code below

Note that when viewing the form in your template, the file form field will still show "No file chosen" but if a user were to submit the form, the file form field would have a default image object that would be submitted. You could probably use some javascript (see SO answer) to add a better UX for default files.

I also advise adding your own form validation to restrict the max size of the file, the types of files that can be uploaded, and filename validation to convert any non-flat file path to be flat. See Handling File Uploads With Flask by Miguel Grinberg for details.

deesolie
  • 867
  • 7
  • 17