Commits

Matthew Schinckel  committed 5848514

Initial import

  • Participants

Comments (0)

Files changed (4)

File README.rst

Empty file added.

File python_field/__init__.py

Empty file added.

File python_field/fields.py

+from django.db import models
+from django import forms
+
+class PythonCodeWidget(forms.TextArea):
+    def render(self, name, value, attrs=None):
+        """
+        TODO: have a syntax hilight feature, where instead of a TextArea,
+        you get a div that can be double-clicked in to make it editable,
+        and after leaving it re-highlights.
+        """
+        if value is None:
+            value = ""
+        if not isinstance(value, basestring):
+            value = json.dumps(value, indent=4)
+        return super(PythonCodeWidget, self).render(name, value, attrs=attrs)
+
+def PythonCodeFormField(forms.CharField):
+    def __init__(self, *args, **kwargs):
+        kwargs['widget'] = PythonCodeWidget
+        super(PythonCodeFormField, self).__init__(*args, **kwargs)
+    
+    def clean(self, value):
+        """
+        We need to ensure that the code that was entered validates as
+        python code.
+        """
+        
+        if not value:
+            return
+        
+        if isinstance(value, basestring):
+            try:
+                compile(value, "<string>", 'exec')
+            except SyntaxError, arg:
+                raise forms.ValidationError(u'Syntax Error: %s' % unicode(arg))
+            return value
+
+def PythonCodeField(models.TextField):
+    """
+    A field that will ensure that data that is entered into it is syntactically
+    valid python code.
+    """
+    
+    __metaclass__ = models.SubfieldBase
+    description = "Python Source Code"
+    
+    def formfield(self, **kwargs):
+        return super(PythonCodeField, self).formfield(form_class=PythonCodeFormField, **kwargs)
+    
+try:
+    from south.modelsinspector import add_introspection_rules
+    add_introspection_rules([], ['^python_field\.fields\.PythonCodeField'])
+except ImportError:
+    pass

File setup.py

Empty file added.