【问题标题】:Why won't date_based.archive_month in Django 1.3 work to show my blog posts?为什么 Django 1.3 中的 date_based.archive_month 不能显示我的博客文章?
【发布时间】:2011-11-04 21:34:01
【问题描述】:

我只是想列出我在某年某月的博客帖子,但我的帖子都没有显示。当我输入正确的 url:2011/nov 时,没有帖子显示,我在我的管理员中保存了 2011 年 11 月的帖子。

另外,由于某种原因,我的 css 文件没有被考虑在内。当我转到 2011 年 11 月的 url 时,我得到的只是没有样式的 html,也没有我的帖子。我在这里做错了什么?

#models.py
class Post(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(max_length=120, unique = True)
    body = models.TextField()
    published = models.DateTimeField(default=datetime.now)
    categories = models.ManyToManyField(Category)

    def __unicode__(self):
        return self.title

#urls.py
info_dict = {
    'queryset': Post.objects.all(),
    'date_field': 'published',
}

urlpatterns = patterns('',
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$',
    date_based.archive_month,
    dict(info_dict, template_name='blog/archive.html',)),

#blog/archive.html
<link href="../static/style.css" rel="stylesheet" type="text/css" media="screen" />
.
.
.
{% for post in post_list %}
<h3 class="title"><a href="{% url single_post slug=post.slug %}">{{post.title}}</a>    
</h3>                        
{% endfor %}

【问题讨论】:

    标签: django blogs archive


    【解决方案1】:
    1. CSS 未显示,因为您将其相对定义为../static/style.css。当地址为/2011/jan 时,浏览器会尝试从/2011/static/style.css 获取css。修复:设置路径为绝对路径:/static/style.css

    2. 您应该循环访问名为 object_list 而不是 post_list 的对象。

      {% for post in object_list %}

    【讨论】:

    • 谢谢!它现在可以工作了,但我为什么必须将它称为 object_list 呢?我尝试设置'template_object_name':'post_list',但这也不起作用。
    【解决方案2】:

    保存帖子的上下文变量称为 object_list 而不是 post_list,因此您应该:

    {% for post in object_list %}
    ...
    {% endfor %}
    

    https://docs.djangoproject.com/en/dev/ref/generic-views/?from=olddocs#django-views-generic-date-based-archive-month

    你的 css 文件应该是:

    如果您在本地开发,则需要设置开发服务器来为您提供媒体服务:

    https://docs.djangoproject.com/en/dev/howto/static-files/#using-django-contrib-staticfiles

    【讨论】:

      【解决方案3】:

      除了上面pastylegs写的,你还应该改这行

      published = models.DateTimeField(default=datetime.now)
      

      到这里:

      published = models.DateTimeField(auto_now_add=True)
      

      在 Python 中,named arguments are only evaluated once。这意味着默认的published 值是您的服务器上次编译models.py 文件的时间。 Django 提供了一个解决方案:设置参数auto_now_add=True,使 django 使用字段的实际当前时间,当它第一次创建时。同样,设置auto_now=True 会使django 为字段设置当前时间无论何时保存

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 2016-05-18
        • 1970-01-01
        • 2023-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多