【问题标题】:Type object 'Post' has no attribute 'published' Django类型对象“发布”没有属性“已发布”Django
【发布时间】:2018-01-24 22:43:47
【问题描述】:

我正在开发一个应用程序,我正在尝试根据标签显示相关帖子。我一切正常,但是当我在浏览器中加载详细视图时,我收到一条错误消息,提示 type object 'Post' has no attribute 'published' 我在下面发布了我的代码。

型号:

class Post(models.Model):
    """docstring for Post."""
    STATUS_CHOICES = (
        ('drafts', 'Draft'),
        ('published', 'Published'), )
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) #blank=True, null=True)#default=1
    title = models.CharField(max_length = 120)
    slug = models.SlugField(unique= True)
    draft = models.BooleanField(default = False)
    publish = models.DateField(auto_now=False, auto_now_add=False)
    content = models.TextField()
    tags = TaggableManager()
    status = models.CharField(max_length=10,choices=STATUS_CHOICES, default='published')
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

查看:

def view(request, slug =None):
    instance = get_object_or_404(Post, slug =slug)
    if instance.draft or instance.publish > timezone.now().date():
        redirect(index)
    #content_type = ContentType.objects.get_for_model(Post)
    #obj_id = instance.id
    initial_data = {
            "content_type": instance.get_content_type,
            "object_id": instance.id
    }
    form = CommentForm(request.POST or None, initial=initial_data)
    if form.is_valid():
        #print  (form.cleaned_data)
        c_type = form.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model= c_type)
        obj_id = form.cleaned_data.get("object_id")
        c_content =form.cleaned_data.get("content")
        parent_obj = None
        try:
            parent_id = int(request.POST.get("parent_id"))
        except Exception as e:
            parent_id = None

        if parent_id:
            parent_query = Comment.objects.filter(parent__id= parent_id)
            if parent_query.exists():
                parent_obj = parent_query.first()

        new_comment, created = Comment.objects.get_or_create(
                user = request.user,
                content_type = content_type,
                object_id = obj_id,
                content = c_content,
                parent = parent_obj,

                )
        return HttpResponseRedirect(new_comment.content_object.get_absolute_url())


    comments = instance.comments
    # List of similar posts
    post_tags_ids = instance.tags.values_list('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=instance.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]
    context = {
    #"objects": query,
    "instance": instance,
    "comments": comments,
    "form": form,
    'similar_posts': similar_posts
    }
    template = 'view.html'
    return render(request,template,context)

添加代码将根据要求添加。提前致谢。

【问题讨论】:

    标签: python django tags


    【解决方案1】:

    将以下属性添加到Post 类:

    class PublishedManager(models.Manager):
          def get_queryset(self):
                return super(PublishedManager,self).get_queryset().filter(status='published')
    
    class Post(models.Model):
       # ...
       objects = models.Manager() # The default manager.
       published = PublishedManager() # Our custom manager.
    

    posts = Post.published.all()                          
    

    【讨论】:

      【解决方案2】:

      如果我理解正确,那么你有一个印刷错误

      similar_posts = Post.published.filter(tags__in=post_tags_ids)
                                           .exclude(id=instance.id)
      

      上面的行应该是

      similar_posts = Post.objects.filter(tags__in=post_tags_ids)
                                           .exclude(id=instance.id)
      

      另外,如果你的意思是使用字段publish,那么它只能在查询集参数中使用,而不是作为相关对象属性

      【讨论】:

      • 天啊。谢谢我真的很喜欢
      猜你喜欢
      • 1970-01-01
      • 2019-12-10
      • 2021-06-08
      • 2022-01-04
      • 2017-06-11
      • 2015-12-06
      • 1970-01-01
      • 2014-05-21
      • 2020-01-12
      相关资源
      最近更新 更多