Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use __repr__ method within django template?

For example, there is an object in a nested loop:

 {% for fieldset in inline_admin_form %}
                    {% for line in fieldset %}
                      {% for field in line %}

                        {% if field.is_hidden %} {{ field.field }} {% endif %}
                      {% endfor %}
                    {% endfor %}
                  {% endfor %}
              {% endif %}

Now I want to check the class name and some information about field.field, so I use field.field.__repr__() to replace field.field.

However, the django template complains about it after the change:

Variables and attributes may not begin with underscores: 'field.field.__repr__'

Does anyone have idea about this? And is there any better way to debug for a variable in django template? (I tried {% debug %} but found it awful when I want to check a variable in a nested loop..)

like image 403
Hanfei Sun Avatar asked Nov 12 '13 06:11

Hanfei Sun


People also ask

How is the __ repr __ magic method used?

In Python, __repr__ is a special method used to represent a class's objects as a string. __repr__ is called by the repr() built-in function. You can define your own string representation of your class objects using the __repr__ method. Special methods are a set of predefined methods used to enrich your classes.

What is the __ repr __ method?

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

Does repr return a string?

The repr() function returns the string representation of the value passed to eval function by default. For the custom class object, it returns a string enclosed in angle brackets that contains the name and address of the object by default.

What is the purpose of __ Str__ method in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.


1 Answers

{{ value|stringformat:'r' }}

uses the string % operator style formatting with the r format which uses repr()

like image 86
Jamie Pate Avatar answered Oct 05 '22 23:10

Jamie Pate