from lxml import etree

from django import forms
from django.db import models


class XMLFileField(models.FileField):
    def __init__(self, *args, **kwargs):
        self.schema = kwargs.pop('schema')
        super(XMLFileField, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        data = super(XMLFileField, self).clean(*args, **kwargs)

        with data as fh:
            doc = etree.parse(fh)

        with open(self.schema) as fh:
            schema = etree.XMLSchema(etree.parse(fh))

        if not schema.validate(doc):
            raise forms.ValidationError('The XML file failed to validate '
                                        'against the supplied schema.')
        return data

[((16, 18, 16, 33), 'lxml.etree.parse', 'etree.parse', ({(16, 30, 16, 32): 'fh'}, {}), '(fh)', False, 'from lxml import etree\n'), ((22, 18, 23, 71), 'django.forms.ValidationError', 'forms.ValidationError', ({(22, 40, 23, 70): '"""The XML file failed to validate against the supplied schema."""'}, {}), "(\n    'The XML file failed to validate against the supplied schema.')", False, 'from django import forms\n'), ((19, 37, 19, 52), 'lxml.etree.parse', 'etree.parse', ({(19, 49, 19, 51): 'fh'}, {}), '(fh)', False, 'from lxml import etree\n')]