检查上下文是模型 django

Check context is model django

我有这样一个模板标签:

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)

它将 link 呈现到对象的管理编辑页面,该对象位于我发送到那里的模板的上下文中:

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

我需要进行测试,如果上下文是字符串或整数或 None,则不会出现错误。我的问题是如何使 "if" 在哪里可以防止出现此错误?

您可能想要使用 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)