【问题标题】:Django functions issue and urlconf confusionDjango 函数问题和 urlconf 混淆
【发布时间】:2012-06-07 16:01:45
【问题描述】:

我无法将我的问题放在一句话中。 我正在按照教程从头开始制作博客。但本教程预测在单独的模板中列出所有类别、标签、月份和年份。

我想在主博客页面上添加类别列表、月份和年份列表。

这就是我得到的。使用此代码,类别列表会显示在主页中,但前提是您转到 blog/category url,而不仅仅是 blog/ 我想要的位置。

    **(r'^$', list),**
    (r'^archive/(\d{1,2})/$', list),
    (r'^\d{2}/d{4}/$', month),
    (r'^([0-9]{4}/\d{1,2})/(?P<slug>.*)/$', detail),
    (r'^(?P<year>\d{4})/$', year),
    **(r'^category/$', category),**

我也试过了:

    (r'^$', category),

但没有运气。

这是 category.html 和 list.html 中模板中的相同代码:

 {% if categories %}
        {% for category in categories %}
        <li class="cat-item"><a href="category/{{ category.name.lower }}/"
            title="{{ category.name.capitalize }}">
             {{ category.name.capitalize }}</a>
         </li>
         {% endfor %}
         {% endif %}

Views.py:

def category(request):
    return render_to_response('blog/list.html', {'categories':Category.objects.all(),},)

是这样的。我试过这个,但在 def list 中没有运气:

return render_to_response('blog/list.html',{'posts':posts,
                                       'next':next,
                                       'previous':previous,
                                       'categories':Category.objects.all(),
                                       },)

我怎样才能让博客/类别上显示的内容也显示在博客/上? 谢谢。

【问题讨论】:

  • list 是 Python 内置函数。我不建议为您的视图列表命名,因为它会影响内置。

标签: django function blogs categories


【解决方案1】:

当您在浏览器中键入 URL 时,请求会发送到您的服务器。 Django 然后获取 url 并将其与 url 模式匹配以确定正确的视图。一旦找到视图,django 就会停止匹配并执行该视图,该视图又会返回响应。

如果您想在不同的视图中使用您的类别,您要么必须确保在每个视图中为模板提供相同的 categories 上下文变量,要么通常更好的是 write a simple custom template tag。对于您的类别,这可能如下所示:

@register.inclusion_tag('blog/category_list.html')
def categories_list():
    return { 'categories': Category.objects.all() }

“blog/categoy_list.html”文件中的代码将是当前位于“categories.html”和“list.html”中的代码。在这些文件中将其替换为。

{% load your_blog_tags %}
{% categories_list %}

您可以在任何需要类别列表的地方使用它。当然,这同样适用于年份和月份列表。

【讨论】:

  • 好的,我做了所有这些,但我仍然一无所获。
  • 你的数据库中有Categories吗?当您执行python manage.py shell 然后import &lt;your_blog_tags&gt;categories_list() 时,您会得到什么?
  • 导入 是什么意思?因为我在我的博客应用程序文件夹中创建了一个 templatetags 文件夹,里面有这些文件: categories_list.py categories_list.pyc init.py init.pyc 。代码是和上面一样。所以我在模板中加载 categories_list 并在我希望它出现的地方有一个 {{ categories_list }}。是的,我在我的数据库中创建了 3 个类别,它们相应地显示在博客/类别页面上。
  • 但是如果他们显示了,那么没有问题!? import &lt;your_blog_tags&gt; 我的意思是from templatetags.categories_list import categories_list
  • 嘿,它成功了,谢谢 :) 抱歉花了几天时间我忘了告诉 :)
猜你喜欢
  • 2021-03-22
  • 2020-05-23
  • 2012-09-25
  • 2015-06-14
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多