Search code examples
pythontemplatesflaskwtformshiddenfield

Getting value of an HiddenField inserting it from template - Flask


I'm a newbie in Python/Flask programmation and I'm having some problems to return the value of my HiddenField inserting it from my template.

This my Form Class:

class DownloadForm(Form):
link = HiddenField()
download = SubmitField('Download')

And this is my template "Material" with a table in which I put my materials from DB and where I'm trying to put the value of the HiddenField:

    <tbody>
    {% for mat in materials %}
      <tr>
        <td>{{ mat.author }}</td>
        <td>{{ mat.title }}</td>
        <td>{{ mat.subject }}</td>
        <td>{{ mat.description }}</td>
                    <td>{{ mat.faculty }}</td>
                    <td>{{ mat.professor }}</td>
                    <td>
          <select class="form-control">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
          </select>
        </td>
          <form method="POST" enctype="multipart/form-data" action={{url_for('download')}}>
          {{ formDownload.link(value = '{{mat.link}}')}}
        <td>{{ formDownload.download }}</td>
          </form>
        <td>{{ formDelete.delete }}</td>
      </tr>
  {% endfor %}
  </tbody>
  </table>

The problem is in this line of code where I would like to insert the HiddenField value.

{{ formDownload.link(value = '{{mat.link}}')}}

I want to insert the value here because every SubmitField is linked with a specific row of the table. The variable mat.link contains the url of the material that users want to download but I can't get this value with the function form.request['link'].

Here there's my function download when form is submitted:

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

form = DownloadForm(csrf_enabled=False)

if form.validate_on_submit():
    link = request.form['link']
    return redirect(url_for('download',
                            filename=link))

I've tried to debug my application and the variable link results equal to "mat.link" as a string . Can someone help me please ? Thanks


Solution

  • In your template, '{{mat.link}}' is a string. If you want the value of mat.link, you need to use it as a variable.

    {{ formDownload.link(value=mat.link) }}