Commits

Valentin Golev committed a6b47a6

Initial commit

  • Participants

Comments (0)

Files changed (7)

+glob:*.pyc
+glob:*.swp
+========================
+  django_templatefield
+========================
+
+This field is used for storing template-strings in database.
+
+NOTE!
+You can't just store django.template.Template() in the field, because we can't
+convert it back to the string. Please store a string with template instead, it
+will be converted to the Template() automagically.
+
+Usage:
+
+1. Add templatefield/ directory to your python import path (for example, copy it
+into the directory with your other apps).
+
+2. Define a form with a template, like:
+
+from templatefield.fields import TemplateField
+
+class Widget(models.Model):
+    template = TemplateField()
+
+3. In the admin, in the form, in the shell or in your app code you can save
+any template string to this field:
+
+>>> from my_app.models import Widget
+>>> w = Widget(template="Hello, {{ username }}!")
+>>> w.template
+<templatefield.fields.StoredTemplate object at 0x2bc0f50>
+
+>>> w.save()
+
+4. Render a template as your usual Template:
+>>> from django.template import Context
+>>> w.template.render(Context({'username': 'Bob Marley'}))
+u'Hello, Bob Marley!'
+

File templatefield/__init__.py

Empty file added.

File templatefield/fields.py

+from django.db import models
+
+from django.template import Template
+
+class StoredTemplate(Template):
+    def __init__(self, tpl, *args, **kwargs):
+        super(StoredTemplate, self).__init__(tpl, *args, **kwargs)
+        self._initial_string = tpl
+
+    def __unicode__(self):
+        return self._initial_string
+
+class TemplateField(models.TextField):
+    __metaclass__ = models.SubfieldBase
+
+    def to_python(self, value):
+        if isinstance(value, StoredTemplate):
+            return value
+        return StoredTemplate(value)
+
+    def get_prep_value(self, value):
+        if isinstance(value, StoredTemplate):
+            return unicode(value)
+
+        return value
+
+try:
+    from south.modelsinspector import add_introspection_rules
+    add_introspection_rules([], ["^templatefield\.fields\.TemplateField"])
+except ImportError:
+    pass

File templatefield/models.py

+from django.db import models
+
+# Create your models here.

File templatefield/tests.py

+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+

File templatefield/views.py

+# Create your views here.