I'm new to Flask. I have a problem with my code. I want my app to delete a specified file in my directory.
First, this is my code for showing all file in a specified directory in the form of a list:
@app.route('/dirfile')
def dirfile():
path = './static/pickle/'
lst = os.listdir(path)
return render_template('dirfile.html', lst=lst)
Here's my dirfile.html code showing all files in directory.
{% for file_name in lst %}
<ul class="list-group ">
<li class="list-group-item ">
<div class="row">
<div class="col">
{{ file_name }}
</div>
<div class="col">
<a
href="{{ url_for('deldir/{{file_name}}') }}"
class="btn btn-danger btn-sm float-right"
>Delete</a
>
</div>
</div>
</li>
</ul>
{% endfor %}
If you notice, I added a delete button to perform deletion in a specified file in the list.
My delete function:
@app.route('/deldir/<string:file_name>')
def deldir(file_name):
path = './static/pickle/'
base = file_name
fullpath = path + base
os.remove(fullpath)
return redirect(url_for('dirfile'))
But it returned the following error:
werkzeug.routing.BuildError: Could not build url for endpoint 'deldir/{{file_name}}'. Did you mean 'dirfile' instead?