0

我有这样一个模板标签:

def link(obj):
    return reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=[obj.id])

class AdminEditNode(template.Node):
    def __init__(self, object):
        self.object = template.Variable(object)

    def render(self, context):
        return link(self.object.resolve(context))

def edit_link(parser, token):
    try:
        #split content
        tag_name, info = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            '%r tag requires one model argument' % token.contents.split()[0])


    return AdminEditNode(info)

register.tag('edit_link', edit_link)

它呈现一个链接到我在视图中发送到那里的模板的上下文中的对象的管理编辑页面:

def home(request):
    """
    Home page view
    """
    context = Contact.objects.first()
    return render(request, 'home.html', {'info': context})

如果上下文是字符串、整数或无,我需要测试不会出现错误。我的问题是如何使“如果”在哪里可以防止此错误?

4

1 回答 1

0

您可能想要使用isinstance. 所以也许是这样的:

class AdminEditNode(template.Node):
    def __init__(self, object):
        self.object = template.Variable(object)

    def render(self, context):
        resolved = self.object.resolve(context)
        if not isinstance(resolved, models.Model):
            # Maybe you want to raise an exception here instead?
            return ''  

        return link(resolved)
于 2016-02-12T19:10:54.090 回答