django - 使用自定义模板标签时出错 - 对象不支持项目分配

标签 django django-templates

我正在尝试创建自己的模板标签。我是如何做到这一点的:

文件夹结构:

my_app/
    __init__.py
    models.py
    views.py
    my_app/
        templates/
            show.html
    templatetags/
            __init__.py
            depos.py

depos.py:

# coding: utf-8
from django import template
from core.models import Depos

register = template.Library()

@register.inclusion_tag('show.html')
def show_dep():
    dep = Depos.objects.all().order_by('?')[0]
    return dep

show.html:

<div id="user_testimonial">
    <blockquote>
        <p>{{ dep.dep }}</p>
        <cite>{{ dep.name }}, {{ dep.from }}</cite>
    </blockquote>
</div>

在我的模板中:

{% load depos %}
{% show_dep %}

但是我遇到了这个错误:

TypeError at /cadastro  
'Depos' object does not support item assignment

最佳答案

您需要将字典对象从包含标记传递到包含标记模板。 It's mentioned in the docs :

First, define the function that takes the argument and produces a dictionary of data for the result. The important point here is we only need to return a dictionary, not anything more complex.

所以尝试一下:

@register.inclusion_tag('show.html')
def show_dep():
    return {
        'dep' : Depos.objects.all().order_by('?')[0]
    }

关于django - 使用自定义模板标签时出错 - 对象不支持项目分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774760/

相关文章:

django - ProgrammingError(模板渲染时出错)

python - Django 图片上传

python - 如何在 Django 中创建单选按钮,哪些字段在表单和模型中使用

javascript - 使用 jQuery 仅更新同一 div 类中的一个元素

python - 呈现 : 'int' object is not iterable in django template 时捕获类型错误

python - MSSQL django_pyodbc 连接问题

Django Admin - 特定用户(管理员)内容

python - 如何从 Django View 中呈现模板标签

html - 如何访问 CSS 中的媒体文件? Django

python - Django block.super 不渲染父模板中设置的变量