Django TypeError - 对象不可迭代

时间:2013-07-28 14:55:49

标签: python django

我正在尝试使用Django,并在尝试访问我定义的网址时遇到以下TypeError: '对象不可迭代'

以下是代码:

models.py

from django.db import models
from django.contrib.auth.models import User
from pubs.models import Pub

# Create your models here.
class Event (models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=500)    
    admin = models.ForeignKey(User)
    def __str__(self):
        return self.name

class Event_Instance (models.Model):
    Event = models.ForeignKey(Event)
    location = models.ForeignKey(Location)
    additional_description = models.CharField(max_length=200)
    display_desc = models.BooleanField(default='true')
    time = models.DateTimeField('Event Date & Time')
    def __str__(self):
        return self.Event.name

urls.py

from django.conf.urls import patterns, url
from events import views

urlpatterns = patterns('',
                       url(r'^(?P<event_id>\d+)/instance/(?P<event_instance_id>\d+)/$',views.event_detail, name='event_detail'),
                       )

views.py

from django.shortcuts import render
from events.models import Event, Event_Instance
from django.http import HttpResponse, Http404


# Create your views here.
def event_detail (request, event_id, event_instance_id):
    try:
        event_instance = Event_Instance.objects.get(pk = event_instance_id)
    except Event_Instance.DoesNotExist:
        raise Http404
    return render(request, 'events/event_instance.html', event_instance)

当我运行Event_Instance.objects.get(pk = 1)时,它会显示我想要的内容,所以它必须与我传入的参数有关,或者我传递了多个参数?< / p>

我错过了一些非常简单的事情吗?

由于

1 个答案:

答案 0 :(得分:4)

render会获取应传递给视图的关键字字典。所以在你的例子中,你应该使用:

return render(request, 'events/event_instance.html', {'event_instance': event_instance})

然后在您的模板中,您可以使用:

{{ event_instance }}
{{ event_instance.location }}
etc.