[Django]-Django Class Based view calling an other one

5👍

The function .as_view() in itself gives back a view function. You have to supply the parameters this way:

return TestToRunPostProcessorView.as_view()(request)
👤Roodie

1👍

I dont think Listview has a post method.

If you want to change the list based on a user input then you have a few different options.

If, for example, you are listing Test items based upon its category you could do:

# 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)

Alternatively, if you want to filter the queryset based upon a submitted input then there is a great example in the book “Two Scoops of Django” which I would highly recommend.

I will not go into all the details but you do add something like:

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

I strongly recommend you to get the book. It will explain it in a lot more detail and give you a lot more options to use it effectively.

1👍

Here is some sample code:

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'),
)

Leave a comment