Django/python: 'function' object has no attribute 'as_view'
Asked Answered
F

1

15

I am trying to create a list_view for a model queryset. When running my server, it returns : attribute error - 'function' object has no attribute 'as_view'. I would appreciate helping me in solve this.

Here's my code:

Views.py:

@login_required 
class live_bids(ListView):

    model = Post 
    template_name = 'loggedin_load/live_bids.html'

    def get_queryset(self):
        return Post.objects.all().prefetch_related('bids').filter(user=self.request.user)

urls.py:

 url(r'^live_bids/$', live_bids.as_view()),
Fasten answered 2/8, 2016 at 15:16 Comment(0)
Y
37

You can't use the login_required decorator on a class like that. You need to use method_decorator. On Django 1.9+, you can decorate the class:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class LiveBids(LoginRequiredMixin, ListView):
    ...

On earlier versions, you need to override dispatch and use method_decorator there.

class LiveBids(LoginRequiredMixin, ListView):
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(LiveBids, self).dispatch(*args, **kwargs)

The easiest solution is to use LoginRequiredMixin instead of the decorator (works with Django 1.9+)

from django.contrib.auth.mixins import LoginRequiredMixin

class LiveBids(LoginRequiredMixin, ListView):
    model = Post 
    template_name = 'loggedin_load/live_bids.html'

    def get_queryset(self):
        return Post.objects.all().prefetch_related('bids').filter(user=self.request.user)

Note that in the examples, I have renamed the view to LiveBids, to match the recommended Django style. You'll have to update the url pattern as well.

Yarrow answered 2/8, 2016 at 15:19 Comment(4)
is there a way to do it for flask?Sterner
@JohnSmith this question has nothing to do with flask. Please ask a new question.Yarrow
doneSterner
this was very useful! Thanks @YarrowClassics

© 2022 - 2024 — McMap. All rights reserved.