【问题标题】:How do I pass multiple class attributes through django to the template?如何通过 django 将多个类属性传递给模板?
【发布时间】:2011-09-16 12:30:07
【问题描述】:

收到此错误: 异常值:
无法解析剩余部分:来自“contact.first_name + contact.last_name”的“+contact.last_name”

我在显示名称列表时遇到问题,每个名称都作为一个链接。

我的 models.py 代码:

class Contact(models.Model):
    first_name = models.CharField("First Name", max_length=30)
    last_name = models.CharField("Last Name", max_length=30)

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

我的views.py代码:

from django.http import HttpResponse
from pk.models import Contact
from django.template import Context, loader
from django.shortcuts import render_to_response

def index(request):
    contact_list = Contact.objects.all()
    return render_to_response('pk/index.html', {'contact_list': contact_list})

我的 index.html 模板:

{% if contact_list %}
<ul>
{% for contact in contact_list %}
    <li><a href="/pkl/{{ contact.id }}/">{{ contact.first_name + contact.last_name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No contacts are available.</p>
{% endif %}

【问题讨论】:

    标签: python html django templates


    【解决方案1】:

    你可以这样做:

    {{ contact.first_name }} {{ contact.last_name }}
    

    Django 不知道如何处理+,你也不需要它。

    【讨论】:

      【解决方案2】:

      对于一个不太长的联系人列表, 例如:

      def index(request):
      contact_list = Contact.objects.all()
      for  i in contact_list:
            contactlist.append(i.first_name + i.last_name)
      return render_to_response('pk/index.html', {'contact_list': contactlist})
      

      【讨论】:

      • python 列表的效率不如说 set 或 tuple 等
      猜你喜欢
      • 1970-01-01
      • 2016-11-17
      • 2013-09-15
      • 1970-01-01
      • 2016-02-15
      • 2012-08-24
      • 2015-11-29
      • 2013-10-09
      • 1970-01-01
      相关资源
      最近更新 更多