基于Django Class的视图调用另一个

时间:2014-07-21 09:14:03

标签: django

我开发了一个基于类的视图来呈现您可以在下面看到的元素列表:

class ConfirmBeforeRunTest(LoginRequiredMixinRedirect,ListView):
    template_name = "app_testing_house/confirm_before_run.html"
    # Redirect to login page if not auth
    redirect_unauthenticated_users = True

    # Options for ListView
    model = Test

    context_object_name = 'test_list'

    def get_queryset(self):
        return Test.objects.filter()

    def post(self, request, *args, **kwargs):
        return TestToRunPostProcessorView.as_view(request) 

正如您所看到的,我希望能够在我的视图中处理POST请求处理,以便为我的查询集获取一些参数。我曾经读过一篇博客,说一个CBV =一个功能。所以我创建了另一个视图来处理所有POST过程:

class TestToRunPostProcessorView(FormView):
    form_class = TestToRunForm

    def form_valid(self, form):
        # Process form
        return self.render_to_response(context)

    def form_invalid(self, form):
        return self.render_to_response(self.get_context_data(form=form))

不幸的是它不起作用,我收到以下错误消息:

as_view() takes exactly 1 argument (2 given)

所以我认为return TestToRunPostProcessorView.as_view(request)不正确,但我不知道为什么......

3 个答案:

答案 0 :(得分:4)

函数.as_view()本身会返回一个视图函数。您必须以这种方式提供参数:

return TestToRunPostProcessorView.as_view()(request)

答案 1 :(得分:1)

我不认为Listview有帖子方法。

如果您想根据用户输入更改列表,那么您有几个不同的选项。

例如,如果您根据类别列出Test项,则可以执行以下操作:

# urls.py
...
    url(regex=r'^category/(?P<category_name>[\w.-]+)/$',
        view=ListByCategory.as_view(),
        name='single_category_list'),

# views.py

class ListByCategory(ListView):
    model = Test
    template_name = 'list_single_category.html'

    def dispatch(self, request, *args, **kwargs):
        self.category = get_object_or_404(Category,
                                          category=self.kwargs['category_name'])

        return super(ListByCategory, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ListByCategory, self).get_context_data(**kwargs)
        context['category'] = self.category
        return context

    def get_queryset(self):
        queryset = super(ListByCategory, self).get_queryset()
        return queryset.filter(category=self.category)

或者,如果你想根据提交的输入过滤查询集,那么书中有一个很好的例子&#34; Django的两个Scoops&#34;我强烈推荐。

我不会详细介绍所有细节,但你会添加类似的内容:

def get_queryset(self):
    queryset = super(ConfirmBeforeRunTest, self).get_queryset()
    q = self.request.GET.get("q")
    if q:
        return queryset.filter(field__contains=q)
    return queryset

我强烈建议你拿到这本书。它将更详细地解释它,并为您提供更多有效使用它的选项。

答案 2 :(得分:1)

以下是一些示例代码:

deprecated_urls = {
   'blog-v1-old-slug': BlogIndexView.as_view(),
   'blog-v2-old-slug': BlogIndexView.as_view(),
}

def route_slug_url(request, slug):
    # 1) match with Node (dynamic slug)
    try:
        nodeslug = NodeSlug.objects.get(slug=slug)
        return BlogNodeView.as_view()(request, node=nodeslug.node)
    except NodeSlug.DoesNotExist:
        pass

    # 2) match with NodeAuthor (dynamic slug)
    try:
        author = NodeAuthor.objects.get(slug=slug)
        return BlogAuthorView.as_view()(request, author=author)
    except NodeAuthor.DoesNotExist:
        pass

    # 3) match with deprecated URL (hard-coded)
    try:
        view = deprecated_urls[slug](request, slug=slug)
        return view
    except KeyError:
        pass

    return serve_404_response(request)

# at end of urls.py, add catch-all for matching slugs
urlpatterns += patterns('', 
    # How to reconcile with local slugs and node slugs?
    url(r'^(?P<slug>[-\w\/\s]+)/$', route_slug_url, name='build-slug'),
)