5

我目前正在学习如何在django 1.3中使用基于类的视图。我试图更新一个应用程序来使用它们,但我仍然不太了解它们是如何工作的(并且我每天阅读整个基于类的视图参考,例如两到三次)。如何在django 1.3中做一个DetailView?

对于这个问题,我有一个空间索引页面需要一些额外的上下文数据,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 

urls.py

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

我错过了DetailView的工作原理?

回答

10

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

此外,如果你定义一个get_object方法,你并不需要的属性querysetmodelslug_field,除非你在get_object或其他地方使用它们。

在上述情况下,你既可以使用你的get_object为你写或定义如下,只有:

model = Space 
slug_field = 'space_name' 
+0

谢谢!我会马上测试代码 – 2011-05-16 09:52:17

相关问题