No escape in a ListView

Hello,
I’m using a ListView based on a template. Nothing original.
However, one of the fields in this template may contain HTML entities (for example: 📞 ) and when my list is displayed, I get the string 📞 instead of the corresponding emoji :telephone_receiver:. This is because the “&” character is escaped as “&”.
How can I get around this escapement?
In my ModelForm, in the clean_myField function, I tried a return mark_safe(data) but it didn’t work.
Thanks for your help.

Side note: A ListView is not “based” on a template. A ListView uses a template for the production of HTML. This distinction is important because in Django, (unlike some other frameworks), the templates are “second-class”. It’s the views that are the “first-class” entities.

You’re on the right track - mark_safe is what you’re looking for - but you need to use it in the production of your context in the view, as a model method, or in the template.

Warning: Marking a field safe that contains user-entered data is dangerous to the stability of your site. It would be very easy for a malicious user to input an HTML fragment - or JavaScript - that breaks your view.

Hello,

Thank you very much for your reply and I’m sorry for my late return.
I apologize for my previous message, which was rather ambiguous due to my poor English.
I used the word “template”, I should have used the word “model”. I apologize.
In the forms.py file, in my class that inherits from ModelForm, I use a clean_myField function like this:

def clean_myField(self):
        data = self.cleaned_data["myField"]
        data = data.replace(":tel:", "📞")
        return mark_safe(data)

That’s not a problem, thanks for the clarification.

Forms are used on data being submitted, not for data being prepared for display as in a ListView. You need to identify the data as safe in the view, a model method, or in the template as described in my previous response.
(Also pay attention to the warning above. If this is user-entered data, you’re potentially creating a vulnerability by marking user-entered data as safe.)

Great!
I put a safe in my template and removed the mark_safe in forms.py.
Conclusion, it works and it’s secure.
However, I don’t know what I would have done if I’d used a view with {{ form.as_p }}…
Thanks again.

Is this user-entered data? If so, how are you securing it? (How are you cleaning the data being entered to ensure there’s no malicious content?)

Different question, different solution.