1

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?

1 Answer 1

1

url_for() needs name of function, not url in route().

Your function has name deldir and it has parameter with name file_name so you have

 url_for('deldir', file_name=file_name)
Sign up to request clarification or add additional context in comments.

1 Comment

thank, it solved my problem. just know url_for can pass paramater too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.