# Buggy code
def validate(self, value, model_instance):
    super(CredentialTypeInjectorField, self).validate(value, model_instance)

    # make sure the inputs are valid first
    try:
        CredentialTypeInputField().validate(model_instance.inputs, model_instance)
    except django_exceptions.ValidationError:
        # If `model_instance.inputs` itself is invalid, we can't make an
        # estimation as to whether our Jinja templates contain valid field
        # names; don't continue
        return

    # In addition to basic schema validation, search the injector fields
    # for template variables and make sure they match the fields defined in
    # the inputs
    valid_namespace = dict(
        (field, "EXAMPLE") for field in model_instance.defined_fields
    )

    class TowerNamespace:
        filename = None

    valid_namespace["tower"] = TowerNamespace()

    # ensure either single file or multi-file syntax is used (but not both)
    template_names = [
        x for x in value.get("file", {}).keys() if x.startswith("template")
    ]
    if "template" in template_names and len(template_names) > 1:
        raise django_exceptions.ValidationError(
            _("Must use multi-file syntax when injecting multiple files"),
            code="invalid",
            params={"value": value},
        )
    if "template" not in template_names:
        valid_namespace["tower"].filename = TowerNamespace()
        for template_name in template_names:
            template_name = template_name.split(".")[1]
            setattr(valid_namespace["tower"].filename, template_name, "EXAMPLE")

    for type_, injector in value.items():
        for key, tmpl in injector.items():
            try:
                Environment(undefined=StrictUndefined).from_string(tmpl).render(
                    valid_namespace
                )
            except UndefinedError as e:
                raise django_exceptions.ValidationError(
                    _("%s uses an undefined field (%s)") % (key, e),
                    code="invalid",
                    params={"value": value},
                )
            except TemplateSyntaxError as e:
                raise django_exceptions.ValidationError(
                    _("Syntax error rendering template for %s inside of %s (%s)")
                    % (key, type_, e),
                    code="invalid",
                    params={"value": value},
                )


# Traceback (AttributeError)
AttributeError: 'super' object has no attribute 'accessible_pk_qs'
2018-03-13 19:49:42,026 ERROR    django.request Internal Server Error: /api/v2/inventory_sources/
Traceback (most recent call last):
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/lib/python2.7/site-packages/awx/wsgi.py", line 65, in _legacy_get_response
return super(AWXWSGIHandler, self)._legacy_get_response(request)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner
return func(*args, **kwargs)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/awx/api/generics.py", line 284, in dispatch
return super(APIView, self).dispatch(request, *args, **kwargs)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/generics.py", line 201, in get
return self.list(request, *args, **kwargs)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/mixins.py", line 45, in list
return self.get_paginated_response(serializer.data)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/serializers.py", line 742, in data
ret = super(ListSerializer, self).data
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/serializers.py", line 660, in to_representation
self.child.to_representation(item) for item in iterable
File "/usr/lib/python2.7/site-packages/awx/api/serializers.py", line 2070, in to_representation
ret = super(InventorySourceSerializer, self).to_representation(obj)
File "/usr/lib/python2.7/site-packages/awx/api/serializers.py", line 683, in to_representation
return super(UnifiedJobTemplateSerializer, self).to_representation(obj)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/serializers.py", line 504, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/rest_framework/fields.py", line 1816, in to_representation
return method(value)
File "/usr/lib/python2.7/site-packages/awx/api/serializers.py", line 346, in _get_summary_fields
return {} if obj is None else self.get_summary_fields(obj)
File "/usr/lib/python2.7/site-packages/awx/api/serializers.py", line 2038, in get_summary_fields
summary_fields = super(InventorySourceSerializer, self).get_summary_fields(obj)
File "/usr/lib/python2.7/site-packages/awx/api/serializers.py", line 1973, in get_summary_fields
summary_fields = super(InventorySourceOptionsSerializer, self).get_summary_fields(obj)
File "/usr/lib/python2.7/site-packages/awx/api/serializers.py", line 407, in get_summary_fields
user_capabilities = self._obj_capability_dict(obj)
File "/usr/lib/python2.7/site-packages/awx/api/serializers.py", line 436, in _obj_capability_dict
model, qs, prefetch_list, view.request.user
File "/usr/lib/python2.7/site-packages/awx/main/utils/common.py", line 571, in prefetch_page_capabilities
filter_args.append(Q(**{'pk__in': model.accessible_pk_qs(user, '%s_role' % role_type)}))
File "/usr/lib/python2.7/site-packages/awx/main/models/unified_jobs.py", line 199, in accessible_pk_qs
return super(UnifiedJobTemplate, cls).accessible_pk_qs(accessor, role_field)
AttributeError: 'super' object has no attribute 'accessible_pk_qs'

# Fixed code
def validate(self, value, model_instance):
    super(CredentialTypeInjectorField, self).validate(value, model_instance)

    # make sure the inputs are valid first
    try:
        CredentialTypeInputField().validate(model_instance.inputs, model_instance)
    except django_exceptions.ValidationError:
        # If `model_instance.inputs` itself is invalid, we can't make an
        # estimation as to whether our Jinja templates contain valid field
        # names; don't continue
        return

    # In addition to basic schema validation, search the injector fields
    # for template variables and make sure they match the fields defined in
    # the inputs
    valid_namespace = dict(
        (field, "EXAMPLE") for field in model_instance.defined_fields
    )

    class TowerNamespace:
        filename = None

    valid_namespace["tower"] = TowerNamespace()

    # ensure either single file or multi-file syntax is used (but not both)
    template_names = [
        x for x in value.get("file", {}).keys() if x.startswith("template")
    ]
    if "template" in template_names and len(template_names) > 1:
        raise django_exceptions.ValidationError(
            _("Must use multi-file syntax when injecting multiple files"),
            code="invalid",
            params={"value": value},
        )
    if "template" not in template_names:
        valid_namespace["tower"].filename = TowerNamespace()
        for template_name in template_names:
            template_name = template_name.split(".")[1]
            setattr(valid_namespace["tower"].filename, template_name, "EXAMPLE")

    for type_, injector in value.items():
        for key, tmpl in injector.items():
            try:
                Environment(undefined=StrictUndefined).from_string(tmpl).render(
                    valid_namespace
                )
            except UndefinedError as e:
                raise django_exceptions.ValidationError(
                    _("{sub_key} uses an undefined field ({error_msg})").format(
                        sub_key=key, error_msg=e
                    ),
                    code="invalid",
                    params={"value": value},
                )
            except TemplateSyntaxError as e:
                raise django_exceptions.ValidationError(
                    _(
                        "Syntax error rendering template for {sub_key} inside of {type} ({error_msg})"
                    ).format(sub_key=key, type=type_, error_msg=e),
                    code="invalid",
                    params={"value": value},
                )