MarkupTextField

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from django.db.models import CharField, TextField
from django.utils.html import linebreaks

MARKUP_CHOICES = (
	('html', 'Plain HMTL'),
	('plain', 'Plain Text'),
)

try:
	from markdown import markdown
	MARKUP_CHOICES += (('markdown', 'Markdown'),)
except ImportError:
	pass

try:
	from textile import textile
	MAKRUP_CHOICES += (('textile', 'Textile'),)
except ImportError:
	pass

class MarkupTextField(TextField):
	"""
	A TextField taht automatically implements DB-cached makup translation.
	
	Supports: Markdown, Plain HTML, Plain Text, and Textile.
	"""
	def __init__(self, *args, **kwargs):
		super(MarkupTextField, self).__init__(*args, **kwargs)
	
	def contribute_to_class(self, cls, name):
		self._html_field = "%s_html" % name
		self._markup_choices = "%s_markup_choices" % name
		TextField(editable=False, blank=True, null=True).contribute_to_class(cls, self._html_field)
		CharField(choices=MARKUP_CHOICES, max_length=10, blank=True, null=True).contribute_to_class(cls, self._markup_choices)
		super(MarkupTextField, self).contribute_to_class(cls, name)
	
	def pre_save(self, model_instance, add):
		value = getattr(model_instance, self.attname)
		markup = getattr(model_instance, self._markup_choices)
		if markup == 'markdown':
			html = markdown(value)
		elif markup == 'plain':
			html = linebreaks(value, autoescape=True)
		elif markup == 'textile':
			html = textile(value)
		else:
			html = value
		setattr(model_instance, self._html_field, html)
		return value
	
	def __unicode__(self):
		return self.attname

More like this

  1. MarkupField by jpt 5 years, 1 month ago
  2. Generic markup converter by ubernostrum 7 years, 1 month ago
  3. Markup Selection in Admin by jonathan 6 years, 8 months ago
  4. render_markup filter, specify the markup filter as a string by exogen 7 years ago
  5. Template Filter: Add indentation by Chuck Harmston 4 years, 7 months ago

Comments

svetlyak (on November 6, 2008):

I belive, that if you don't want to call markdown or any other postprocessor at any page view, then you should use Cache.

Storing additional data in the database is a bad idea, if you want to archieve a performance.

#

daevaorn (on November 6, 2008):

But it is the cache itself. Local cache of text field that stored in database. Whats wrong?

#

(Forgotten your password?)