Search code examples
djangopython-3.xdjango-modelsdjango-viewsattributeerror

AttributeError - 'DeferredAttribute' object has no attribute 'all'


I keep getting an error in posts = Post.published.all()

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse


class Post(models.Model):
STATUS_CHOICES = (
     ('draft','Draft'),
     ('published','Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
                         unique_for_date='published')
author = models.ForeignKey(User,
                           related_name='blog_posts',
                           on_delete=models.CASCADE)
body = models.TextField()
published = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
                          choices = STATUS_CHOICES,
                          default='draft')
def get_absolute_url(self):
    return reverse('blog:post_detail',
                   args=[self.publish.year,
                         self.publish.strftime('%m'),
                         self.publish.strftime('%d'),
                         self.slug])

class Meta:
    ordering = ('-published',)


def __str__(self):
    return self.title  

views.py

from django.shortcuts import render, get_object_or_404
from .models import Post

def post_list(request):
posts = Post.published.all()
return render(request,
              'blog/post/list.html',
              {'posts': posts})

def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
                               status='published',
                               publish_year=year,
                               publish_month=month,
                               publish_day=day)

And I keep getting this error whenever i run my server...

AttributeError at /blog/ 'DeferredAttribute' object has no attribute 'all'

from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.published.all() ...

Also some tips to make my own blog page would be helpful


Solution

  • You need to use objects instead of published

    posts = Post.objects.all()
    

    If you want to filter published post then use this:

    posts = Post.objects.filter(status='published')