Object html representation in Django

点点圈 提交于 2019-12-13 21:19:16

问题


I have written a python app which as a result creates a list of Result objects. I've written a method which makes a html representation of the object Result, showing its main attributes.

class Result():

    def to_html(self):
        num_of_exp = "Number of exponentials: %s"% self.number_of_exponentials
        function = "Function: %s"% self.function
        par_of_exp = "Parameters of exponentials: <br /> %s "% pprint.pformat(self.parameters_of_exponentials)
        chunk = "Chunk: <br /> %s"% pprint.pformat(self.chunk)
        backgrnd = "Background <br /> %s" % pprint.pformat(self.background)
        raw_par_of_exp = "Raw parameters of exponentials: <br /> %s"% pprint.pformat(self.raw_parameters)
        non_phy = "Non physical solution:  %s" % pprint.pformat(self.non_physical_solution)
        user_choice = "User choice:  %s" %  pprint.pformat(self.user_choice)

        output = (function + r"<br /><br />" + num_of_exp + r"<br /><br />"+ par_of_exp + r"<br /><br />" + 
              backgrnd+ r"<br /><br />" + non_phy + r"<br /><br />"
              )

        return output

I'm using Django to make a web interface for the application.

I made a Django template:

...
<body>

{% for result in result_list %}
{{result.to_html}}
{% endfor %}


</body>

And added return render_to_response('result_pick.html',{'result_list': rp.parsed_output_data })

where rp.parsed_output_data is a list of Result objects (the size of the list is not fixed).

The output i get completely ignores the html tags in to_html(). Html source of the output:

Function: 98.627732*2.71828182845905**(-0.016052058*t)&lt;br /&gt;&lt;br /&gt;Number of exponentials: 1&lt;br ... ...

What i have to get as a final result are representations of Result objects displayed in a nice human readable format, each in its own divs and form with a next button. So when the user selects a Result he is transfered to another page where additional details are shown.

I'm looking for advices on how to do this the right and most clean way. Any comment is appreciated. Tnx


回答1:


Html tags are ignored / autoescaped for safety see here and here.

The right way would be constructing html output through django templating system and not within object itself e.g.:

<body>

{% for result in result_list %}
Function: {{ result.function }}<br /><br />
Number of exponentials: {{ result.number_of_exponentials }}<br /><br />
...
{% endfor %}

</body>


来源:https://stackoverflow.com/questions/11102485/object-html-representation-in-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!