【问题标题】:Django Template is Printing Object Representation instead of Object ValueDjango 模板正在打印对象表示而不是对象值
【发布时间】:2019-03-17 18:40:27
【问题描述】:

views.py

@login_required 
def ManageDomain(request): 
    AssocNotAuthDomains = Tld.objects.filter(FKtoUser_id=request.user,auth=0)
    AssocAuthDomains = Tld.objects.filter(FKtoUser_id=request.user,auth=1)

    return render(request, 'site/account/template.html', {
         'AssocNotAuthDomains':AssocNotAuthDomains,
         'AssocAuthDomains':AssocAuthDomains
    })

template.html

{% if AssocAuthDomains or AssocNotAuthDomains  %}
<div class="acctDomains">
    <h3 class="Titles"><img src="{% static "img/templated/acct/AuthDomainSm.png" %}" width="22" height="22" alt="Authorized Domain(s)" /> Verified Domains</h3>
    <ul>
    {% for authdomain in AssocAuthDomains %}
        <li>{{ authdomain }}<span><a class="scan" href="/Account/PerformScan/?d={{ authdomain }}">Scan now</span></a></li>
    {% endfor %}
    </ul>
    <h3 class="Titles"><img src="{% static "img/templated/acct/UnAuthDomain.png" %}" width="22" height="22" alt="Unverified Domain(s):" /> Unverified Domains</h3>
    <ul>
    {% for notauthdomain in AssocNotAuthDomains %}
        <li>{{ notauthdomain }}<span><a class="scan" href="Verify Now">Verify now</span></a></li>
    {% endfor %}
    </ul>
</div><!--acctDomains-->

打印出来:

Tld object (1)

Tld object (2)

而不是值,例如websiteabc.com

我做错了什么?

谢谢

【问题讨论】:

    标签: python django templates view


    【解决方案1】:

    如果你想渲染这样的模型实例,你必须在你的模型中实现__str__

    class Tld(models.Model):
        def __str__(self):
            # return something meaningful here like self.some_attribute
    

    或者你必须像这样在模板中显式使用属性

     {{ authdomain.some_attribute }}
    

    否则,python 不知道如何从要显示的对象中获取有意义的东西。

    【讨论】:

      【解决方案2】:

      这是因为您试图显示整个对象,而不是值。

      你需要更换

      {{ notauthdomain }}
      

      与

      {{ notauthdomain.name }} 
      

      将“名称”替换为您的值的字段名称 - websiteabc.com

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-12
        • 1970-01-01
        相关资源
        最近更新 更多