Reputation: 69795
I am trying to display a form that uses Font Awesome icons. I have the field emotion
which contains EMOTIONS
as choices, and I want to display the font awesome icon related to each option. I have tried just adding the markup (see the last option of EMOTIONS
). However, this is rendering exactly the pure text instead of the icon.
Is it possible to display the Font Awesome icon in the way I am trying? This is my form:
class PreferencesForm(forms.Form):
EMOTIONS = [
('😂', 'Joy'),
('😢', 'Sad'),
('😡', 'Angry'),
('😫', 'Tired'),
('🙂', '<i class="far fa-smile"></i>'),
]
FAMOUS_PEOPLE = [
('US', 'Abraham Lincoln'),
('MX', 'Frida Khalo'),
('IT', 'Leonardo da Vinci'),
('FR', 'Napoleon Bonaparte'),
('JP', 'Hayao Miyazaki'),
]
emotion = forms.ChoiceField(choices=EMOTIONS, widget=forms.RadioSelect())
famous_person = forms.ChoiceField(choices=FAMOUS_PEOPLE, widget=forms.RadioSelect())
This is my markup:
<form action="." method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
How can I display the corresponding font awesome icon instead of the markup?
I have tried {{ form|safe }}
, but it hasn't worked.
Upvotes: 2
Views: 277
Reputation: 69795
The solution is to use mark_safe
.
So I was struggling for an hour, and I decided to ask a question, and I was able to figure it out approximately 20 minutes after I posted it after seeing that safe
was used in templates to render HTML
.
Therefore, my form ended up being as follows:
from django.utils.safestring import mark_safe
class PreferencesForm(forms.Form):
EMOTIONS = [
('😂', 'Joy'),
('😢', 'Sad'),
('😡', 'Angry'),
('😫', 'Tired'),
('🙂', mark_safe('<i class="far fa-smile"></i>')),
]
FAMOUS_PEOPLE = [
('US', 'Abraham Lincoln'),
('MX', 'Frida Khalo'),
('IT', 'Leonardo da Vinci'),
('FR', 'Napoleon Bonaparte'),
('JP', 'Hayao Miyazaki'),
]
emotion = forms.ChoiceField(choices=EMOTIONS, widget=forms.RadioSelect())
famous_person = forms.ChoiceField(choices=FAMOUS_PEOPLE, widget=forms.RadioSelect())
No changes were required in the HTML.
Upvotes: 2