2013-04-02 9 views
2

我正試圖創建自己的模板標籤。我是如何做到了這一點:使用自定義模板標記時出錯 - 對象不支持項目分配

文件夾結構:

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 

回答

5

你必須傳遞一個字典對象從包含標籤到你的包含標籤的模板。 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] 
    } 
相關問題