5

我目前正在学习如何在 django 1.3 中使用基于类的视图。我正在尝试更新应用程序以使用它们,但我仍然不太了解它们是如何工作的(而且我每天都会阅读两到三遍整个基于类的视图参考)。

对于这个问题,我有一个需要一些额外上下文数据的空间索引页面,url 参数是一个名称(没有 pk,并且无法更改,这是预期的行为)以及没有该空间的用户在他们的个人资料中选择无法进入。

我的基于函数的代码(工作正常):

def view_space_index(request, space_name):

    place = get_object_or_404(Space, url=space_name)

    extra_context = {
        'entities': Entity.objects.filter(space=place.id),
        'documents': Document.objects.filter(space=place.id),
        'proposals': Proposal.objects.filter(space=place.id).order_by('-pub_date'),
        'publication': Post.objects.filter(post_space=place.id).order_by('-post_pubdate'),
    }

    for i in request.user.profile.spaces.all():
        if i.url == space_name:
            return object_detail(request,
                                 queryset = Space.objects.all(),
                                 object_id = place.id,
                                 template_name = 'spaces/space_index.html',
                                 template_object_name = 'get_place',
                                 extra_context = extra_context,
                                )

    return render_to_response('not_allowed.html', {'get_place': place},
                              context_instance=RequestContext(request))

我的基于类的视图(不工作,不知道如何继续):

class ViewSpaceIndex(DetailView):

    # Gets all the objects in a model
    queryset = Space.objects.all()

    # Get the url parameter intead of matching the PK
    slug_field = 'space_name'

    # Defines the context name in the template
    context_object_name = 'get_place'

    # Template to render
    template_name = 'spaces/space_index.html'

    def get_object(self):
        return get_object_or_404(Space, url=slug_field)

    # Get extra context data
    def get_context_data(self, **kwargs):
        context = super(ViewSpaceIndex, self).get_context_data(**kwargs)
        place = self.get_object()
        context['entities'] = Entity.objects.filter(space=place.id)
        context['documents'] = Document.objects.filter(space=place.id)
        context['proposals'] = Proposal.objects.filter(space=place.id).order_by('-pub_date')
        context['publication'] = Post.objects.filter(post_space=place.id).order_by('-post_pubdate')
        return context

网址.py

from e_cidadania.apps.spaces.views import GoToSpace, ViewSpaceIndex
urlpatterns = patterns('',
    (r'^(?P<space_name>\w+)/', ViewSpaceIndex.as_view()),
)

我缺少什么让 DetailView 工作?

4

1 回答 1

10

我在您的代码中看到的唯一问题是您的 url 的 slug 参数被命名'space_name'而不是'slug'. 视图的slug_field属性是指将用于 slug 查找的模型字段,而不是 url 捕获名称。在 url 中,您必须命名参数'slug'(或者'pk',当使用它时)。

此外,如果您正在定义一个get_object方法,则不需要属性queryset,modelslug_field,除非您在您的get_object或其他地方使用它们。

在上述情况下,您可以使用您get_object所写的内容,也可以仅定义以下内容:

model = Space
slug_field = 'space_name'
于 2011-05-16T04:44:40.140 回答