Home > Mobile >  Django - TypeError: object of type 'method' has no len()
Django - TypeError: object of type 'method' has no len()

Time:11-27

I was trying add paginator to my website using some online code but I'm getting this error return len(self.object_list) TypeError: object of type 'method' has no len()

Views.py

def sample(request):

    WAllPAPER_PER_PAGE = 2
    wallpapers = Wallpaper.objects.all
page = request.GET.get('page', 1)
wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE)
try:
    wallpapers = wallpaper_paginator.page(page)
except EmptyPage:
    wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages)
except:
    wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE)
context = {"wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator}
return render(request, "Wallpaper/sample.html", context )

Models.py

class Wallpaper(models.Model):
    name = models.CharField(max_length=100, null=True)
    size = models.CharField(max_length=50, null=True)
    pub_date = models.DateField('date published', null=True)
    resolution = models.CharField(max_length=100, null=True)
    category = models.ManyToManyField(Category)
    tags = models.ManyToManyField(Tags)
    Device_Choices = [
        ('PC', 'pc'),
        ('mobile', 'mobile')
    ]
    Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC')
    image = models.ImageField(upload_to='Wallpaper/Images/', default="")

    def __str__(self):
        return self.name

enter image description here

CodePudding user response:

You need to call .all(), otherwise it is a reference to a method, so you work with:

#                     call .all() ↓↓
wallpapers = Wallpaper.objects.all()

The reason that you need to call this is because the Paginator expects something that is iterable and has a length, like a list or a QuerySet.

  • Related