Use icon in wtforms SubmitField?
Answer a question
I know this looks like a duplicate of this similar question, in which the answer gives two solutions. But these solutions don't work for me. I am trying to rewrite this html to be rendered with wtforms. I have an < i > tag with a font-awesome icon inside a button tag:
<button id="symbolBtn" class="mybtn btn btn-outline-secondary" type="submit"
name="submit-button" value="search">
<i class="fas fa-search"></i>
</button>

The first solution to the similar question suggests using Markup to define the html to be used as a value - for this solution I am trying this:
from markupsafe import Markup
BuyForm(FlaskForm):
# The fields in question:
search = StringField("Search", id="symbolInput", validators=[validSymbol])
search_icon = Markup("<i class="fas fa-search"></i>")
search_button = SubmitField(search_icon, id="symbolBtn")
# Other fields in the same form
shares = IntegerField("Shares", id="amountInput", validators=[validBuyAmount])
shares_button = SubmitField("Refresh", id="amountBtn")
submit_button = SubmitField("Buy")
I have multiple SubmitFields (submit buttons) and validate differently depending what SubmitField was pressed. But the icon isn't rendered - the html string is being rendered as text in the button. I can see that the quotation marks are a problem and I've tried differnet combinations:
Markup('<i class="fas fa-search"></i>')
Markup("<i class='fas fa-search'></i>")
Markup("<i class=\"fas fa-search\"></i>")
etc... But each attempt just renders text. Like where the html source on inspect is, for example:
value="<i class='fas fa-search'></i>"

Which I guess is logical, so how is it that people get this to work?
The second solution in the similar question suggests writing it out as plain html, but I need to check which button was pressed from the custom wtforms validators, for example validSymbol(form, field) for which I need to be able to say:
if form.search_button.data:
# Search button was pressed. Check if search field contains valid data.
Is what I want to do not possible or am I just missing something?
Answers
I don't know if you ever figured it out and Markup was not working for me either but here is what i did.
In my forms i made a class and submitfield
class FavoriteForm(FlaskForm):
favorite = SubmitField('Favorite')
In my routes i did
if fav.validate_on_submit:
if fav.data['favorite']: # If favorite comes back True
#code
return redirect(url_for('home'))
and in my html i did
<form method="POST">
{{ fav.hidden_tag() }}
<button type="submit" name="favorite" value="x" class="follow-btn"><i class="fa fa-heart-o"> Favorite</i></button>
</form>
Your button has to have a name and a value. name has to be the name you used for your SubmitField in your forms and value can be what ever you want it to just not empty.
更多推荐

所有评论(0)