Code

Ticket #5620: newforms_xmlfield2.diff

File newforms_xmlfield2.diff, 2.0 KB (added by teepark, 6 years ago)
Line 
1Index: django/db/models/fields/__init__.py
2===================================================================
3--- django/db/models/fields/__init__.py (revision 7534)
4+++ django/db/models/fields/__init__.py (working copy)
5@@ -1157,6 +1157,11 @@
6         self.schema_path = schema_path
7         Field.__init__(self, verbose_name, name, **kwargs)
8 
9+    def formfield(self, **kwargs):
10+        defaults = {'form_class': curry(forms.XMLField, schema_path=self.schema_path)}
11+        defaults.update(kwargs)
12+        return super(XMLField, self).formfield(**defaults)
13+
14     def get_manipulator_field_objs(self):
15         return [curry(oldforms.XMLLargeTextField, schema_path=self.schema_path)]
16 
17Index: django/newforms/fields.py
18===================================================================
19--- django/newforms/fields.py   (revision 7534)
20+++ django/newforms/fields.py   (working copy)
21@@ -32,7 +32,7 @@
22     'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
23     'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
24     'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
25-    'SplitDateTimeField', 'IPAddressField', 'FilePathField',
26+    'SplitDateTimeField', 'IPAddressField', 'FilePathField', 'XMLField'
27 )
28 
29 # These values, if given to to_python(), will trigger the self.required check.
30@@ -782,3 +782,19 @@
31 
32     def __init__(self, *args, **kwargs):
33         super(IPAddressField, self).__init__(ipv4_re, *args, **kwargs)
34+
35+class XMLField(CharField):
36+    """
37+    A field that validates XML content against a RelaxNG schema
38+    """
39+    def __init__(self, schema_path=None):
40+        self.schema_path = schema_path
41+
42+    def clean(self, value):
43+        from django.core.validators import RelaxNGCompact, ValidationError as OldValidationError
44+        if self.schema_path:
45+            try:
46+                RelaxNGCompact(self.schema_path)(value, "")
47+            except OldValidationError, e:
48+                raise ValidationError(e.messages)
49+        return value