如何通过 Django 将多个类属性传递给模板?

0 投票
2 回答
1236 浏览
提问于 2025-04-17 02:25

出现了这个错误:
异常信息:无法解析剩余部分:' + contact.last_name' 来自 'contact.first_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 %}

2 个回答

0

对于一个不是很长的联系人列表,比如:

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})
4

你可以直接这样做:

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

Django不知道怎么处理这个+,而且你也不需要它。

撰写回答