How to prevent Flask-WTF forms from closing modal when submitting invalid input?
I am trying to build a website where you can upload a video (this already works). But when submitting a wrong file format, the Flask-WTF form closes the modal. I want it to stay open.
(I am trying it first with an image PNG)
This is the form:
class VideoUploadForm(FlaskForm):
video = FileField('Upload video', validators=[FileAllowed(['png']), FileRequired()])
submit = SubmitField('Upload')
This is the route:
@main.route("/video", methods=['GET', 'POST'])
@login_required
def video():
form = VideoUploadForm()
if form.validate_on_submit():
f = form.video.data
filename = secure_filename(f.filename)
f.save(os.path.join(
os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)), 'static\\videos', filename
))
flash('Video has been succesfully uploaded', 'success')
return redirect(url_for('main.video'))
return render_template('video.html', title='Upload video', form=form)
This is the modal:
<div class="modal fade mt-5" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Upload video</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<div class="modal-body">
{% if form.video.errors %}
{{ form.video(class="form-control form-control-lg is-invalid") }}
<p class="mt-1 ml-1"><small>Allowed formats: mov, mp4</small></p>
<div class="invalid-feedback">
{% for error in form.video.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.video }}
<p class="mt-1 ml-1"><small>Allowed formats: mov, mp4</small></p>
{% endif %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
{{ form.submit(class="btn btn-primary") }}
</div>
</form>
</div>
</div>
</div>
How to prevent the modal from closing when I try to upload a jpg file for example? For now it will close the modal and if opened again it shows the error message. But i want it to stay open so that you immediately can see the error message.
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
How to clear user uploaded images if the limit of files exceeded in jquery
I have a simple form where a user can upload multiple images. I only want the user to upload 4 images at once, so I did the following:
$("#myfile").on("change", function() { if ($("#myfile")[0].files.length > 4) { alert("You can select only 4 images"); } });
<input type="file" id="myfile" class="form-control" name="pimage[]" multiple="multiple">
This gives an alert when the user uploads more than 4 images but doesn't stop them from submitting the form.
Can anyone please tell me how to clear the user uploaded images if the limit exceeds or disable the submit button?
-
Setting A $_GET Value From A Previously Defined Variable - PHP
I have a search form in the header of every page on a site that submits info to another page when undertaking a search query via the form's
action
attribute, namely a page calledsearch.php
and it takes the value of the search<input>
field and stores it as a variable calledsearchQuery
. Using PHP this searches a MySQL database. All of this works as expected.I would like the value of the search input field to be placed in the URL of the page the search is processed on, again namely
search.php
.I understand from other questions on SO that you can't add variables to a form's
action
attribute. If I add the key of the query string in the action attribute, the form still works OK:action="search.php?keyword="
From this I thought I would be able to then set the
$_GET
value on thesearch.php
page by using:if(isset($_POST['search-submit'])) { // make this variable available before HTML output $searchQuery = htmlspecialchars($_POST['search']); $_GET['keyword'] = $searchQuery; }
This however does not work, although it doesn't throw any errors in my PHP error logs.
Because I'm running the script on specific page allocated by the action attribute, I don't think I need to use a
$_SESSION
variable?HTML Form
Here is the form that is on every page in the header
<form action="search.php?keyword=" method="POST"> <label for="search">Enter Search</label> <input type="search" name="search" id="search"> <button type="submit" name="search-submit" id="search-submit">Search</button> </form>
-
How do I set default alignment for horizontal controls in Bootstrap-UI 3 for CakePHP 4?
This is a particularly obscure question about the Boostrap-UI plugin for CakePHP but I'm hoping someone might be able to help.
I’m using Bootstrap-UI (https://github.com/FriendsOfCake/bootstrap-ui) version 3.0, so using Bootstrap 4.6.
I’m trying to create a form that has controls that are aligned horizontally with their labels using the example from the readme here -
This works fine except I can’t see how to define the default column distribution ie so that the classes for the label and the control container are something like
col-4
andcol-8
without any breakpoint defined.If I try something like -
'align' => [ 'left' => 4, 'middle' => 8, ]
The classes created are
col-md-4
andcol-md-8
ie it seems to default to md as the breakpoint for the columns.I know this is a bit obscure but does anyone have any idea how to do what I want?
-
Images with Firebase and Python Flask API
I am currently developing an API using Firebase from google and Python's Flask libraries. It is a proyect where I am in need of saving images to the DB and then adress them in the API. I would also like to know how to relate the image to an item in the database, say posting an image of Juan, and that is linked with ALL the information from Juan inside the DB. Thanks!
-
Pandas 1.4.2 upgrade casuing FFlask: array(0.78015261) (0d array) is not JSON serializable at the moment
We upgraded to a newer version of python with new pandas, numpy, etc. The versions are now:
- python=3.10.4 - pandas=1.4.2 - numpy=1.22.3
In previous versions, the error never occurred. When I do some debugging, it's not that the
.to_json()
is wrong or fails, it's that thepd.DataFrame([my_result])
doesn't return correctly.The code is this:
// Used in debugging and doesn't return properly dataframe_test = pd.DataFrame([my_result]) // Error gets thrown here return pd.DataFrame([my_result]).to_json()
The
dataframe_test
looks like this when I go to view it in Data Viewer within VS Code (it also keeps processing as the data seems to still be running in VS Code - the bar above the viewer is indicating that its still trying to run/process):The
my_result
variable looks like this upon entering the dataframe:I am not sure what exactly is causing the issue and not sure how to debug in Pandas to see what is happening. Any ideas?
-
Flask select which form to POST by button click
I'm trying to have only one of two forms POST depending on which button from a btn-group is selected. Currently all of the forms POST with no issue, but there are two forms where only one or the other value is needed. I've unsuccessfully tried to parse the not needed value out at the app.py, so I decided to try and make this so only one or the other value gets posted.
Here is the code from the .html where I'm having trouble, it's a fieldset from a larger form the rest of which is working for now.
<fieldset class="row mb-3, container" id="program_value_form_id"> <legend for="value_range" class="col-sm-2 col-form-label">Value Range:</legend> <p> <div class="btn-group, com-sm-1" role="group" aria-label="Basic radio toggle button group"> <input type="radio" onchange="swapConfig(this)" class="btn-check" name="btnradio_valuer" id="btnradio_value1" autocomplete="off" value="valuerange1" checked> <label class="btn btn-outline-primary" for="btnradio_value1">100-200</label> <input type="radio" onchange="swapConfig(this)" class="btn-check" name="btnradio_valuer" id="btnradio_valuer2" autocomplete="off" value="valuerange2"> <label class="btn btn-outline-primary" for="btnradio_valuer2">400-500mhz</label> </div> </p> <div id="btnradio_valuer1Swap"> <label for="value" class="col-sm-2 col-form-label">Value:</label> <p> <div class="col-sm-4"> <input id="value1" type="number" class="form-control" placeholder="xxx.xxx 100-200" name="value1" step="0.001" min="100" max="200"> <span class="validity"></span> </div> </p> </div> <div id="btnradio_valuer2Swap" style="display:none"> <label for="value" class="col-sm-2 col-form-label">Value:</label> <p> <div class="col-sm-4"> <input id="value2" type="number" class="form-control" placeholder="xxx.xxx 400-500" name="value2" step="0.001" min="400" max="500"> <span class="validity"></span> </div> </p> </div> </fieldset>
The forms swap depending on button click. Here is the js for that I got from on here to swap them.
<script> function swapConfig(x) { var radioName = document.getElementsByName(x.name); for(i = 0 ; i < radioName.length; i++){ document.getElementById(radioName[i].id.concat("Swap")).style.display="none"; } document.getElementById(x.id.concat("Swap")).style.display="initial"; } </script>
I have tried if statements and if's inside of for's, none have worked. In frustration I've deleted them, but I could try and rewrite them again if they are needed though I wouldn't expect much from them since my html experience is limited. Please let me know if there needs to be any corrections to what I've written or if there is a better way or place to do what I am trying to do.
-
How to get conf value from airflow dag?
I want to get conf value from dag area.
"{{ dag_run.conf['company'] }}"
is recognized as a string.How can I get this value?
Values are passed fine when calling other dags.
t_trigger = TriggerDagRunOperator( task_id="t-trigger", trigger_dag_id="example_dag", conf={ "company": "{{ dag_run.conf['company'] }}", }, )
However, in the dag area the value is recognized as a string.
t_task_a = PythonOperator( task_id="t-task-a", python_callable=task-a, ) employees = Variable.get( "{{ dag_run.conf['company'] }}", # problem default_var=['company'], deserialize_json=True ) for employee in employees: t_employee_operator = PythonOperator( task_id=f"t-test-operator", python_callable=employee_operator, op_kwargs={"employee": employee} ) t_task_a >> t_employee_operator
-
How can I alternate the elements of multiple lists in Ansible?
I have multiple lists as input (all lists have the same length, but the input can have more than 3 lists). I want to create a list which is a sum of all input lists alternating their elements.
For example, given the following input:
data: - ['1','2','3','4','5'] - ['6','7','8','9','10'] - ['11','12','13','14','15']
I'm expecting the following output:
lst: [['1','6','11'],['2','7','12'],['3','8','13'],['4','9','14'],['5','10','15']]
This is what I've tried:
--- - name: zip more than 3 lists with loop hosts: localhost tasks: - name: Set facts set_fact: list: - ['1','2','3','4','5'] - ['6','7','8','9','10'] - ['11','12','13','14','15'] - name: zip to make pairs of both lists set_fact: lst: "{{ list[0] | zip(list[1]) | zip(list[2]) | list }}" - name: Debug ['1','6','11'],['2','7','13'],... debug: msg: "{{ item | flatten }}" loop: "{{ lst }}" - name: zip to make pairs of both lists set_fact: lst2: "{{ lst2 | default([]) | zip(ansible_loop.nextitem) | list }}" loop: "{{ list }}" loop_control: extended: yes - name: Debug debug: msg: "{{ lst2 }}"
The first
set_fact
outputs loop elements butlst
doesn't include the actual output I expect. And the limitation of the firstset_fact
is that I can't iterate in the loop due tozip
filter. I don't know how to acheive my goal. -
How to properly give sql alchemy quary with relations to WTForms?
I have a problem that I'm working on several days.
I have a Flask app and in some place I want to edit some data in my DB. Data model I want to edit is similar to(using Flask-SQLAlchemy):
class User(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(64)) last_name = db.Column(db.String(64)) address = db.relationship('Address', backref='user', lazy='dynamic') class Address(db.Model): id = db.Column(db.Integer, primary_key=True) street = db.Column(db.String(64)) region = db.Column(db.String(64)) user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
Having defined model, I designed next form:
class AddUser(FlaskForm): first_name = StringField("first_name", validators=[ InputRequired()]) last_name = StringField("last_name", validators=[ InputRequired()]) region = StringField("region", validators=[ InputRequired()])
In Flask, edit function looks like this:
@app.route('/edit_user/<int:id>', methods=['GET', 'POST']) def edit_user(id): qry = User.query.filter_by(id=id).first() if qry: form = AddUser(obj=qry) if request.method == 'POST' and form.validate(): # save edits qry.first_name = form.first_name .data qry.last_name = form.last_name.data qry.address.region = form.region.data db.session.commit() flash('Socnet updated successfully!') return redirect(url_for("view_record", user=form.id.data, level='overview')) return render_template('add_user.html', form=form, id=id) else: return 'Error loading #{id}'.format(id=id)
Unfortunately, the form looks like
First name: My_name Last name: My_lastname Region: [<Address 1>]
So it looks like WTForms doesn't know what to do with relationships. If I write the template manually, I will use it like
qry.adrress.region
and it would work without any problems, but I really don't want to build the forms by myself.This case is not unique. The same issues arises with a table autogeneration module.
I know I miss something valuable. Please, help.
-
Cannot open image using Pillow
I'm making a flask application for converting image formats, everything went well until it came to using Pillow, I can't even open the image even though it exists in the given path
Traceback (most recent call last): File "/data/data/com.termux/files/home/flask_projects/converter_website/env/lib/python3.10/site-packages/flask/app.py", line 2095, in __call__ return self.wsgi_app(environ, start_response) File "/data/data/com.termux/files/home/flask_projects/converter_website/env/lib/python3.10/site-packages/flask/app.py", line 2080, in wsgi_app response = self.handle_exception(e) File "/data/data/com.termux/files/home/flask_projects/converter_website/env/lib/python3.10/site-packages/flask/app.py", line 2077, in wsgi_app response = self.full_dispatch_request() File "/data/data/com.termux/files/home/flask_projects/converter_website/env/lib/python3.10/site-packages/flask/app.py", line 1525, in full_dispatch_request rv = self.handle_user_exception(e) File "/data/data/com.termux/files/home/flask_projects/converter_website/env/lib/python3.10/site-packages/flask/app.py", line 1523, in full_dispatch_request rv = self.dispatch_request() File "/data/data/com.termux/files/home/flask_projects/converter_website/env/lib/python3.10/site-packages/flask/app.py", line 1509, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "/data/data/com.termux/files/home/flask_projects/converter_website/app.py", line 24, in index foo(filename, filename_without_extension, path_to_converted_file) File "/data/data/com.termux/files/home/flask_projects/converter_website/app.py", line 13, in foo file = Image.open(".user_images/" + filename) File "/data/data/com.termux/files/home/flask_projects/converter_website/env/lib/python3.10/site-packages/PIL/Image.py", line 3123, in open raise UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file '.user_images/aFrFkNJV-JE9ExzDh6nnlOBXi16cYOKSf14D02qLQQpOwEgf_XtzKX-Jo2a8X6BmRKmKgHytpbWrbkzG4vtQFPr.jpg'
Here is the code
@app.route("/", methods=["POST", "GET"]) def index(): form = ConversionForm() if form.validate_on_submit(): file = form.file_for_conversion.data filename = secure_filename(file.filename) filename_without_extension = re.sub(r"\.[a-z]{3,}$", "", f"{filename}") # this regex remove file extension from end of filename path_to_converted_file = ".user_images/" + filename_without_extension + "." +form.filetype.data print(filename, filename_without_extension, path_to_converted_file, sep="\n") file = Image.open(file) return render_template("index.html", form=form)
help me please
I found a solution - the image was corrupted