I have an
EmployeeForm
with one of the fields comprising of a
PhotoForm
shown below:
class EmployeeForm(Form):
name = StringField('Full Name', validators=[DataRequired()])
title = StringField('Job Title', validators=[DataRequired()])
email = StringField('Company Email', validators=[DataRequired()])
department = StringField('Department', validators=[DataRequired()])
photo = FormField(PhotoForm)
Depending on whether a USE_S3 config variable is set to True or False I want two fields on my photo object to be automatically set to default values like so:
class PhotoForm(Form):
image = S3ImageUploadField(base_path=app.config['UPLOAD_FOLDER'],namegen=photo_name_generator)
if app.config['USE_S3']:
image_storage_type = HiddenField('s3')
image_storage_bucket_name = HiddenField(app.config['S3_BUCKET_NAME'])
else:
image_storage_type = HiddenField('empty string')
image_storage_bucket_name = HiddenField('empty string')
However, when I check the form's html there is no hidden field nor when I check the database on submission is there any set values on the image_storage_type and image_bucket_name and I can't figure it out why that is. I've checked on some stackoverflow questions but they don't exactly fit my question because I am using Flask-Admin and WTForm together which in my opinion makes it a little more trickier.
Also, my admin.py file for the form rendering looks like this:
class EmployeeView(ModelView):
form = EmployeeForm
I'm not sure if this is a problem on WTForm's side or Flask-Admin's side but I've been trying for a long time to make this work. Does anyone has any ideas? Help would be greatly appreciated.
Accepted answer
The first argument for a field is its label. In your code you aren't passing data into the field, you are setting its label. Set the default data with the default kwarg.
from wtforms import Form, HiddenField
class PhotoForm(Form):
default_image_data = "foo" if True else "bar"
image_storage_type = HiddenField('image storage', default=default_image_data)
>>> form = PhotoForm()
>>> form.image_storage_type.data
'foo'
>>> form.image_storage_type()
u'<input id="image_storage_type" name="image_storage_type" type="hidden" value="foo">'
Why is my WTForm HiddenField not being set to a default value?
SelectMultipleField default value is not being selected on HTML
How do you set a default value for a WTForms SelectField?
Set default value for select html element in Jinja template?
How to dynamically set default value in WTForms RadioField?
Flask default error handler not being called
How to set default value using SqlAlchemy_Utils ChoiceType
Python session SAMESITE=None not being set
Why is my Flask error handler not being called?
How do I set the default value of a relationship field in flask_admin based on the url parameter?
SQLAlchemy/WTForms: set default selected value for QuerySelectField
How to set the default value for float in sqlalchemy?
Flask-SQLAlchemy set relationship default value
WTForms: how do I set a default value for an HTML5 Widget?
Flask-wtf can't set default value for DateTimeField
Can I set a StringField's default value outside the field constructor?
using datetime.utcnow() to set default value in flask-sqlalchemy
Cookies not being set with Flask JWT extended
Cookies not being set even with CORS enabled in Flask app
Can't set default value for form data in Flask
flask+marshmallow set default value if value is invalid
Default value not working for reflected model in flask-sqlalchemy
Flask session not persisting value set by ajax if there is no return statement
Why are instances from my code not being added to my database?
How can I dynamically set a default value for a WTForms FormField?
SQL Alchemy/ Flask / WTF Forms set a default value for a queryselectfield
Flask-WTF FieldList of RadioFields not allowing dynamic default value
Flask Sqlalchemy, field does not have a default value
How to set the default value of a field in the database model class to the return value of a function?
Why are tables not being created in flask SQLAlchemy?
Why is only the product, and not its associated movements, being deleted?
Flask WTForms HiddenInput value not being sent to app
Authentication login Cookies not being set in browser - Flask backend API + Angular 7 frontend
Flask sessions: PERMANENT_SESSION_LIFETIME not being set correctly
Why are my ports not being mapped in docker-compose?
Why is the render_template not being expressed?
Why my file is not being downloaded (Flask)
Value of of SelectField in Python Flask is not being displayed correctly
How do I set default value for Flask-WTF in Jinja
Python Flask - How to set a default value of NULL for type Date in a form
WTForm modelform not displaying checkbox value from db record
Set default value in QuerySelectField (Form initialized by object)
Python Flask: Cannot find a way to set the default value in SelectForm (Flask WTF)
Why doesn't my selected value from SQLite database put into a python variable not equal the same string in a different variable?
flask sqlalchemy wtf QuerySelectField returning duplicates and add a default value not in the db
Set Column default value to NULL
For flask how can I set the value for a custom input, but not get placeholder?
Why am I not being redirected when I should
secret key not set in flask session, using the Flask-Session extension
Flask Value error view function did not return a response
More Query from same tag
Docker error : MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
Design patterns for flask API implementation
Axios POST Method: 405 Method Not Allowed
deploy to docker , cannot load stylesheet and javascript
Flask-Dance Error: Scope has changed
centos server anaconda re-install and setting
add token to endpoint for goolge cloud function python
i am trying to create a simple api to recieve any format of json data but getting 400 bad request.. please have a look to my code and correct
Flask/Werkzeug debugger, process model, and initialization code
read contents of a file and display it on browser
Flask import error "cannot import name 'Flask'"
JavaScript CSS Modal not displaying correct info
Flask Unittest for Post Method
Seeking references and advice for modeling time series data in Mongoengine
understanding flask hierarchy in case of rendering user input of one HTML page into an other one (jinja, render_template)
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'posted'
Storing multiple files with the same name in Google Cloud Storage?
Button click in HTML to update SQLAlchemy db in Flask
Protect contact form API
Heroku - downloaded files are taking over 30 seconds to process with AWS
Flask Hello World error
Wtforms: Best way to split a form across multiple pages?
Read CSV file to Flask Restful API using cURL
Access multiplie attributes in a single SQLAlchemy validator
Python3 bcrypt, pymongo, flask ValueError: Invalid salt
how to make bootstrap 4 cards according to mongodb json response?
Import a module from the root
Flask import not registering route
weird bug with submit flask
Pass parameter to json.dumps()
Call a Flask app with gunicorn from python module
python flask sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) attempt to write a readonly database
how to debug a flask app when running in docker
uwsgi upstart on amazon linux
How to render one html file from several html in a loop?
import the dataset in Python with sci-kit learn for machine learning problems_dataset Winscosin breast cancer
How to check if a classifier belongs to sklearn.tree?
How to calculate Sensitivity, specificity and pos predictivity for each class in multi class classficaition
reason for transposed confusion matrix in heatmap
kaggleword2vec utility not found
Loading your own text dataset to scikit-learn
How to change the function a random forest uses to make decisions from individual trees?
Scikit-learn: don't use some words as one word feature, but use in collocations
Scikits-learn svm SVC simple issue
Handling text data with Tensorflow 2 "ERROR: Attempted to pad to a smaller size than the input element"
How to pass input to 2D Conv in Keras?
Compute the mean for each row from a tf.SparseTensor in TensorFlow
Why do the keras loss functions reduce the dimensionality by one?
Log device info in DNNClassifier estimator in Tensorflow
do I have to reinstall tensorflow after changing gpu?
Does Distributed TensorFlow support InfiniBand interconnections "out of the box"
Keras - Translation from Sequential to Functional API
Model training fails with h2o deepwater
ResNet50 network in Keras functional API (python)
Flask: BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand
Flask-SqlAlchemy - Foreign key associated with column ‘ ’ could not find table
Reload systemd/gunicorn/flask worker threads sequentially for config changes
Flask site loads locally but fails on production (PythonAnywhere)
goJS dropdown remove items
How to call a function asynchronously in Flask?
Modify or change relationship properties in py2neo
What is the meaning of a forward slash "/" in a Python method signature, as shown by help(foo)?
Python class accessible by iterator and index
Practical example of Polymorphism
Break or exit out of "with" statement?
seaborn distplot / displot with multiple distributions
Web scraping - how to identify main content on a webpage
'order' of unordered Python sets
tqdm: 'module' object is not callable