python - Django 博客文章未返回

标签 python django

我对 Django 非常陌生,并且一直在阅读《Django 示例》一书中的博客教程。

下面的代码应该返回所有状态为“已发布”的博客文章,但它不起作用。使用 list.html 代码加载看似正确的页面,但没有显示任何帖子。我已经仔细检查过,并且正在使用管理站点创建帖子,并将状态设置为“已发布”。我不确定问题是否出在模板、模型、 View 或 URL 上,因此我将其全部包含在这里:

模型.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse

#Data model class for creating posts table enrties in database

#Custom manager. Limits returned querysets to ones with published status
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager, self).get_queryset()\
    .filter(status='published') #super used to call get_queryset method from parent class as it is currently being
                                #overridden here.

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='publish')    #A field for use in building urls
    #slug = models.SlugField(slugify(title))
    author = models.ForeignKey(User, related_name='blog_posts') #Each post written by a user and a user can write many posts
    body = models.TextField()
    publish = 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')

    objects = models.Manager() #The default manager
    published = PublishedManager() #Custom manager

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

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'),self.publish.strftime('%d'), self.slug])

views.py:

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


def post_list(request):
    posts = Post.objects.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)
    return render(request, 'blog/post/detail.html', {'post':post})

URL.py

from django.conf.urls import url
from . import views

urlpatterns = [
    # post views
    url(r'^$', views.post_list, name='post_list'),
    url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
        r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'),

模板base.html:

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
        <link href="{% static "css/blog.css" %}" rel="stylesheet">

</head>
<body>
    <div id="content">
        {% block content %}
        {% endblock %}
    </div>
    <div id="sidebar">
        <h2>My Site site</h2>
            <p>This site is all about me</p>
    </div>
</body>
</html>

详细信息.html:

{% extends "blog/base.html" %}

{% block title %}My Blog{% endblock %}

{% block content %}
    <h1>Blog</h1>
    {% for post in posts %}
    <h2>
        <a href="{{ post.get_absolute_url }}">
            {{ post.title }}
        </a>
    </h2>
    <p class="date">Published{{ post.publish }} by {{ post.author }}</p>
    {{ post.body|truncatewords:30|linebreaks }}
    {% endfor %}
{% endblock %}

最佳答案

您需要使用 Post.published.all() 来使用您的自定义管理器,然后在您的字典中您正在使用大写 P 进行“帖子”,您可能想尝试小写,因为您的 View 是使用帖子。然后它的值也是一个字符串而不是变量 posts。所以这样的事情应该有效

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

关于python - Django 博客文章未返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42397422/

相关文章:

python - 使用正则表达式在python中解析消息通知索引

python - 事件任务是 Spark UI 中的负数

python - 在 GAE Python 上以编程方式打印 html 标签

python - 异步长时间运行操作 API 调用

django - 通过 Ajax 返回渲染的 Html

python - 我在 Django 中的 urls.py 中的 url 模式不匹配

python - multiprocessing.pool.map 和带有两个参数的函数

python - Ubuntu 18.04 上的 JModelica

python - 如何优化以下Python函数以使其执行速度更快?

python - django项目中的动态子域和url路径