简体   繁体   中英

How to disable escape for Django model field's value in template when rendering fields manually

I am working on one of my colleague's Django (Django 2.1.4) projects. I spent a couple of days to try to figure out how to disable auto escape for Form field's value when rendering it manually in a template. {% autoescape off %} and {{form1.LastName | safe }} {% autoescape off %} and {{form1.LastName | safe }} all don't work.

Here are some relative codes.

Form.py

class tblstudentinfomodelform_page1(forms.ModelForm):
    LastName = forms.CharField(max_length=30, required=True)

views.py

def application(request,application_num)
   form1 = tblstudentinfo.objects.get(ApplicationNumber=application_num)
   ...
   form1_forms = tblstudentinfomodelform_page1(initial=form1.__dict__) if form1 else tblstudentinfomodelform_page1(initial=form1)
   ...
   return render(request,'appinfo.html',{'form1':form1_forms})

appinfo.html

<th>{{form1.LastName}}<br>{{form1.LastName.errors}} {{form1.LastName.value}} </th>

Some tests here:

LastName's value is &#350;haha

test1 : add {% autoescape off %} at the top of the template and {% endautoescape %} at the bottom

result1 : {{form1.LastName.value}} displays correctly -- Şhaha, but input textbox shows &#350;haha run result -- html page

test2 : delete autoescape tag and add safe filter

<th>{{form1.LastName | safe}}<br>{{form1.LastName.errors}} {{form1.LastName.value |safe}} </th>  

result2 : get the same result, looks like that safe filter only worked on form.field.value

Any suggestion?

Thank you.

Add the answer to here in case someone gets the same problem.

Create a function to unescape all HTML entities.

from html import unescape
def html_unescape(data_model):  # convert to unicode characters 
# Convert all named and numeric character references (e.g. &gt;, &#62;, &#x3e;) in the string s to the corresponding Unicode characters. 
    for f in data_model._meta.get_fields():
        if ( f.get_internal_type() == "CharField" or f.get_internal_type() == "TextField") and getattr(data_model, f.name):
            #some old records haved escaped many times
            str = unescape(unescape(unescape(unescape(unescape(getattr(data_model, f.name))))))
            setattr(data_model, f.name, str)
    return data_model

and then

form1 = tblstudentinfo.objects.get(ApplicationNumber=application_num)
form1 = html_unescape(form1)

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