呈现时捕获到AttributeError:“unicode”对象没有属性“\u default\u manager”

2024-04-24 08:51:21 发布

您现在位置:Python中文网/ 问答频道 /正文

遵循Django实用教程得到这个错误。我已经搜索过这里和谷歌,但没有找到任何关于这一点的信息,所以我想这将是我很容易错过的东西。甘比诺例外_标签.py公司名称:

context[self.varname] = self.model._default_manager.all()[:self.num]

在模型.py在

^{pr2}$

甘比诺_标签.py在

from django import template
from django.db.models import get_model

def do_latest_content(parser, token):
    bits = token.contents.split()
    # Checks to make sure that there are 5 words in the tag
    if len(bits) != 5:
        raise template.TemplateSyntaxError("'get_latest_content' tag takes exactly four arguments")
    model_args = bits[1].split('.')
    # Checks to make sure first argument is appname.model name
    if len(model_args) != 2:
        raise template.TemplateSyntaxError("First argument to 'get_latest_content' must be an 'application name'.'model name' string")
    model = get_model(*model_args)
    # Checks to make sure model is != none
    if model is None:
        raise template.TemplateSyntaxError("'get_latest_content' tag got an invalid model: %s" % bits[1])
    return LatestContentNode(bits[1], bits[2], bits[4])

class LatestContentNode(template.Node):
    def __init__(self, model, num, varname):
        self.model = model
        # convert num to int
        self.num = int(num)
        self.varname = varname

    def render(self, context):
        # uses default manager for Entry.live.all() instances
        context[self.varname] = self.model._default_manager.all()[:self.num]
        return ''

register = template.Library()
register.tag('get_latest_content', do_latest_content)

在基本.html在

        {% load gambino_tags %}
        <h2>Five latest entries:</h2>
        <ul>
            {% get_latest_content gambino.entry 5 as latest_entries %}
            {% for entry in latest_entries %}
            <li>
                <a class="list" href="{{ entry.get_absolute_url }}">{{ entry.title }}</a>
                Posted {{ entry.pub_date|timesince }} ago.
            </li>
            {% endfor %}
        </ul>
        <h2>Five latest links:</h2>
        <ul>
            {% get_latest_content gambino.link 5 as latest_links %}
            {% for link in latest_links %}
            <li>
                <a href="{{ link.get_absolute_url }}">{{ link.title }}</a>
                Posted {{ link.pub_date|timesince }} ago.
            </li>
            {% endfor %}
        </ul>

谢谢!在


Tags: toselfgetmodeltaglinktemplateh2
1条回答
网友
1楼 · 发布于 2024-04-24 08:51:21

您的Nodemodel参数是一个字符串(或者至少,这就是您要传递的内容),而不是Model对象。在

bits = token.contents.split()
...
return LatestContentNode(bits[1], bits[2], bits[4])
...
class LatestContentNode(template.Node):
    def __init__(self, model, num, varname):
    self.model = model
...
context[self.varname] = self.model._default_manager.all()[:self.num]

也许你真的是说。。。在

^{pr2}$

是吗?在

相关问题 更多 >