Skip to content
Advertisement

‘function’ object has no attribute ‘objects’ Django, help me

I’m designing a Django app and experiencing an error message:

AttributeError at /
'function' object has no attribute 'objects'
Request Method:
GET
Request URL:
http://127.0.0.1:8000/
Django Version:
2.2.10
Exception Type:
AttributeError
Exception Value:
'function' object has no attribute 'objects'

This is my views.py that generates the message:

from django.shortcuts import render
from post.models import posts


def index(request):
    featured = Post.objects.filter(featured=True)
    context = {
        'object_list': featured
    }
    return render(request, 'index.html', context)

def blog(request):
    return render(request, 'blog.html', {})

def Post(request):
    return render(request, 'post.html', {})`

and this is my model.py

from django.db import models
from django.contrib.auth import get_user_model


user = get_user_model()

class author(models.Model):
    user = models.OneToOneField(user, on_delete=models.CASCADE)
    profile_picture = models.ImageField

class category(models.Model):
    title = models.CharField(max_length=20)

    def __str__(self):
        return self.title

class posts(models.Model):
    title = models.CharField(max_length=100)
    overview = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    comment_count = models.IntegerField(default=0)
    author = models.ForeignKey(author, on_delete=models.CASCADE)
    thumbnail = models.ImageField()
    categories = models.ManyToManyField(category)
    featured = models.BooleanField()

    def __str__(self):
        return self.title

Thanks for any help.

Advertisement

Answer

You wrote a view function named Post, hence Post.objects refers to the Post function, not the model. You furthermore named your model posts, instead of Post. I strongly advise to rename your model to Post, since Django models are normally singular, and written in PerlCase:

from django.shortcuts import render
from post.models import posts


def index(request):
    featured = posts.objects.filter(featured=True)
    context = {
        'object_list': featured
    }
    return render(request, 'index.html', context)

def blog(request):
    return render(request, 'blog.html', {})

def post(request):
    return render(request, 'post.html', {})

Of course then you should rename the variables accordingly.

Advertisement