Hardware, programming and astronomy tutorials and reviews.

nicEditor in Django

Integrating BBCode editing, image upload and other nicEdit features with Django

nicedit is a nice WYSIWYG editor that can be embedded in your pages. It also has two interesting features - BBCode editing and image uploading directly from the editor. In this article I'll show you how to install the editor and support local file uploading as well as BBCode support.

Installing the editor

Uploading images to server

Edycja BBCode

nicEdit can also edit HTML content but return BBCode version of it. This can be used on discussion boards and other pages. To use BBCode output you have to pass bbCode: true in the nicEdit configuration. When you submit the form - it will send the BBCode version. To edit BBCode you have to parse it to X/HTML before sending it to the editor - using some Python based parser.

You can also use a simple function that supports the basic BBCodes. For example Django template tag:
from re import findall

from django import template
from django.conf import settings

register = template.Library()

def fbc(value):
	# strip HTML at start
	# here
	# then:
	value = value.replace("'", ''').replace('"', '"')
	tags = findall( r'(?xs)\[url=(.*?)\](.*?)\[/url]''', value)
	for i in tags:
		value = value.replace('[url=%s]%s[/url]' % (i[0], i[1]), '<a href="%s">%s</a>' % (i[0].replace('"', ''), i[1]))
	value = value.replace('[b]', '<b>')
	value = value.replace('[/b]', '</b>')
	value = value.replace('[i]', '<i>')
	value = value.replace('[/i]', '</i>')
	value = value.replace('[u]', '<u>')
	value = value.replace('[/u]', '</u>')
	value = value.replace('[quote]', '<blockquote>')
	value = value.replace('[/quote]', '</blockquote>')
	value = value.replace('[url]', '')
	value = value.replace('[/url]', '')
	value = value.replace('
', '<br />')
	tags = findall( r'(?xs)\[img\](.*?)\[/img]''', value)
	for i in tags:
		if not len(i) < 3:
			value = value.replace('[img]%s[/img]' % i, '<img src="%s" alt="" />' % i)
	return value

register.filter('fbc', fbc)

Django web framework tutorials, 12 December 2010,

Comment article