Search code examples
djangotemplatetag

Check context is model django


I have such a templatetag:

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)

It renders a link to a admin edit page of the object that is in the context of the template that I send there in my view:

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

I need to make test that there won`t be errors if context would be a string or integer or None. My question how to make "if" where I can prevent this errors ?


Solution

  • You'll probably want to use isinstance. So maybe something like this:

    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)