简体   繁体   中英

Use WTForms RadioField subfields to display an image in Flask

I am using a WTForm form to try to transmit the path to an image I want to display in HTML. My form looks basically like this

from flask_wtf import FlaskForm
from wtforms import RadioField

class SelectStyleForm(FlaskForm):
     images = RadioField('style image.',
                         choices=[(value1, label1),(value2, label2),...])

My goal is to iterate over the different choices to display the image associated to each path next to the corresponding radio button. My HTML template looks like this :

 {% block content %}

 <form method=post>
      {% for subfield in styleform.images %}
           <td>{{subfield}}</td>
           <p>{{subfield.label}}</p>
           <img src="{{url_for('data_path', filename=subfield.label)}}"/>
      {% endfor %}
 </form>
 {% enblock %}

right now, the radio button is displayed along with the name of the file (which is written in the <p> tag), but I can't find a way to have that same name affected to filename .

Right now, the value it refers to is :

<label for="images-1">value1</label>

Is there a way tp affect the "correct" value in the url_for function ? Please note that I would also accept a solution for which the value part of the different choices is used, as they are supposed to be the same path

Alrigth, by fiddling around with the different methods, I discovered that each subfield has a data attribute that stores the string of the label part.

So my code works simply by changing the source of the image :

<img src="{{url_for('data_path', filename=subfield.data)}}"/>

My best guess is that the .label attribute is already attributed to something else in the url_for function and that prevents it to access the string corresponding to the label.

Feel free to correct me if I am wrong or do not hesitate to post a more detailed answer !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM