无法访问Django模板中的属性

时间:2013-06-21 17:30:32

标签: django templates model attributes

查看:

def details(request, id):
    event = Event.objects.filter(id=id)
    return render(request, 'details.html', {'Event' : event})

模板:

{% if Event %}

    <h1>Event Name: {{ Event.name }}</h1>

{% else %}

    No Event.

{% endif %}

型号:

class Event(models.Model):
    name = models.CharField(max_length = 30)
    artist = models.ManyToManyField(Artist)
    venue = models.ForeignKey(Venue)
    event_date = models.DateTimeField('event date')
    on_sale = models.DateTimeField('on sale time')


    def __unicode__(self):
        return unicode(self.name)

当我加载页面时,它只会加载Event Name:。当我删除.name属性时,它会加载事件,因为它在数据库中输入,但它不会从对象加载任何属性。感谢任何帮助/建议,谢谢。

1 个答案:

答案 0 :(得分:5)

您应该使用get而不是filter:

event = Event.objects.get(id=id)

如果你想在模板中使用滤镜,请尝试:

{% for item in Event %}
    <h1>Event Name: {{ item.name }}</h1>
{% empty %}
    No Event.
{% endfor %}