0

我正在尝试开始使用 Django,并在尝试访问我定义的 url 时收到以下 TypeError:'object is not iterable'

这是代码:

模型.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

网址.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'),
                       )

视图.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)它时,它会显示我想要的东西,所以它一定与我传入的参数有关,或者我传入的参数不止一个?

我错过了一些非常简单的东西吗?

谢谢

4

1 回答 1

4

render接受应该传递给视图的关键字字典。因此,在您的示例中,您应该使用:

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

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

{{ event_instance }}
{{ event_instance.location }}
etc.
于 2013-07-28T15:01:39.107 回答