【问题标题】:A basic django inclusion_tag not working一个基本的 django 包含标签不起作用
【发布时间】:2013-04-14 03:45:57
【问题描述】:

我写了一个小的 django 自定义模板标签 (inclusion_tag),我想用它来显示一个 html 表格,显示我的 VehicleBrand 和 VehicleModel 模型中的车辆品牌和型号列表,但是模板标签似乎不是将模板标签中的数据库查询中的变量传递给 html。我是 django 的新手,所以如果我遗漏了一些明显的东西,请告诉我。任何帮助都将不胜感激。

这是我的模板标签,它位于我的应用程序下的模板目录中。模板标签目录包含一个 _init_.py

from django import template
from castester.models import VehicleBrand

register = template.Library()

@register.inclusion_tag("brand_model_select.html")
def brand_model_select():
    brand_list = VehicleBrand.objects.all()
    return {'brand_list':brand_list}

这是我的model.py

from django.db import models

class VehicleBrand(models.Model):
    description = models.CharField(max_length=100)
    code = models.SlugField(primary_key=True)

这是我的brand_model_select.html

{% load castest_extras %}
<table>
    {% for brand in brand_list %}
        <tr>
            <td>{{ brand.code }}</td>
            <td>{{ brand.description }}</td>
        </tr>
    {% endfor %}
</table>

这是我从基于类的视图中调用我的 html 的 urls.conf 行。

url(r'^$', TemplateView.as_view(template_name='brand_model_select.html'))

这是模型查询的输出,用于证明正在从数据库中检索数据。

>>> from castester.models import VehicleBrand
>>> VehicleBrand.objects.all().values()
[{'code': u'1', 'description': u'FORD'}, {'code': u'2', 'description': u'HOLDEN'}]

使用以下源呈现空白页面。我从包含标签传递的查询输出在哪里?

<table>

</table>

【问题讨论】:

  • 请阅读文档中的code layout 部分:Custom template tags and filters must live inside a Django app. If they relate to an existing app it makes sense to bundle them there; otherwise, you should create a new app to hold them. The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

标签: django django-templates


【解决方案1】:

您不打算直接渲染brand_model_select.html。相反,您应该从不同的模板调用您的模板标签:

# in url conf
`url(r'^$', TemplateView.as_view(template_name='homepage.html'))`

# in homepage.html
{% load castest_extras %}
{% brand_model_select %}

包含标记的意义​​在于您可以将其包含在另一个视图中。您现在所做的根本不使用模板标签;相反,它只是渲染brand_model_select.html,完全忽略标签。

【讨论】:

  • 这让我想知道为什么 OP 认为他根本需要包含标签。
  • 感谢 Dougal - 成功了!!!我只是一个初学者,所以我只是开始掌握一些概念。你的回答真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 2012-01-23
相关资源
最近更新 更多