Login

MarkupTextField

Author:
myles
Posted:
November 6, 2008
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

I updated MarkdownTextField to have some choices in markup. It currently support for Markdown, Textile, Plain Text, and Plain HTML. It will add %s_html for the complied HTML and %s_markup_choices for a drop down of markup choices.

Usage:

class MyModel(models.Model):
    description = 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 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?

#

Please login first before commenting.