Search code examples
pythondjangodjango-class-based-views

Django class-based view


Django

Following the official documentation, I am creating a Django app (the same poll app as in the documentation page). While using the class-based view, I got a error. I did not understand much about class based view, for instance, may someone explain, what is the difference between a class based view from a normal view?

Here's my code:

class DetailView(generic.DetailView):
    model = Poll
    template_name = 'polls/details.html'
    def get_queryset(self):
        
    def detail(request, poll_id):
        try:
            poll = Poll.objects.get(pk=poll_id)
        except Poll.DoesNotExist:
            raise Http404
        return render(request, 'polls/details.html', {'poll': poll})

*********************Error ********************
TypeError at /polls/2/results/
as_view() takes exactly 1 argument (3 given)
Request Method: GET
Request URL:    <app-path>/polls/2/results/
Django Version: 1.5.1
Exception Type: TypeError
Exception Value:    
as_view() takes exactly 1 argument (3 given)    

*****the url***
 url(r'^(?P<pk>\d+)/$', views.DetailView.as_view, name='detail')

Solution

  • as_view should be called, not referenced, according to the docs, your url should look like:

    url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail')
    

    Note the usage of parenthesis.

    Also, you should rather call your class PollDetailView to avoid confusion for code readers.

    Also, the detail() method you have defined will not be called at all. So you shouldn't define it at all. Also, leave the get_queryset() method alone for the moment, try to get the basic View to work first.