import inspect
from django import template
from django.forms import FormFieldWrapper
from django.conf import settings

register = template.Library()

@register.filter
def get_form_data(field):
    """If the object passed in is a form field, then return .data, otherwise
    return the object. This allows code like:
       {{ obj.field|get_form_data }}
    which will work if the 'obj' is a Form object, or the actual model object.
    Means the same template code can be used for both previewing form data
    wiki style and displaying the actual object.
    """
    if isinstance(field, FormFieldWrapper):
        return field.data
    return field

@register.filter
def get(container, key):
    """behaves like the default django variable lookup system but with the
    order:
        dictionary lookup
        index lookup
        attribute lookup
        method call
        
    TEMPLATE_STRING_IF_INVALID will be returned if the lookup fails
        (i.e. invalid key, index, attrib name, or method raised error)
    If TEMPLATE_DEBUG is True, method errors will be raised.
    """
    try:
        return container[key]
    except TypeError:
        try:
             value = getattr(container, key)
        except AttributeError:
            return settings.TEMPLATE_STRING_IF_INVALID
        else:
            if inspect.ismethod(value):
                try:
                    return value()
                except:
                    if settings.TEMPLATE_DEBUG:
                        raise
            return value
    except KeyError, IndexError:
        return settings.TEMPLATE_STRING_IF_INVALID
    except:
        if settings.TEMPLATE_DEBUG:
            raise
    return settings.TEMPLATE_STRING_IF_INVALID
