您的位置:首页 > 编程语言 > Go语言

django form 自定制widget

2012-07-06 14:28 183 查看
为了在django中应用百度的ueditor,所以必须自己写个widget。

项目名:mynote

步骤1:

确定STATIC_URL :

vim mynote/mynote/settings :

STATIC_ROOT = os.path.join(HERE,'static').replace('\\','/')

STATIC_URL = '/static/'


步骤2:

python manage.py  startapp rte
#创建一个rte 的app


步骤3:

在rte app 里面 创建三个文件夹:

mkdir static
mkdir templates
mkdir ueditor


步骤4:

下载ueditor ,解压到static 目录中,选择你的app目录里的static

yeelone@yee:~/workspace/mynote/myapp/static$ ls
ueditor


步骤5:前面都是准备工作,现在开始编写widget:

cd   rte/ueditor

touch __init__.py
touch widgets.py


from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _

class Ueditor(forms.Textarea):
class Media:
css ={'all': (settings.STATIC_URL + 'ueditor/themes/default/ueditor.css') , }
js = ("%sueditor/editor_config.js" % settings.STATIC_URL )

def __init__(self,attrs={}):
super(Ueditor,self).__init__(attrs)
def render(self,name,value,attrs=None):
rendered = super(Ueditor,self).render(name,value,attrs)
context = {
'name':name,
'STATIC_URL':settings.STATIC_URL,
}

return rendered + mark_safe(render_to_string('ueditor.html',context))


然后再切换到templates 目录中:

rte/templates
vim ueditor.html
<link  type="text/css"  rel="stylesheet" href="/static/ueditor/themes/default/ueditor.css" />   <script type="text/javascript" src=\'#\'" /static/ueditor/editor_all_min.js" ></script>   <script type="text/javascript" src=\'#\'" /static/ueditor/editor_config.js" ></script>

<script type="text/plain" id="myEditor" name="myContent">
</script>

<script type="text/javascript">
var editor = new baidu.editor.ui.Editor({
initialContent:'',
toolbars: [[ 'undo', 'redo', 'bold', 'italic', 'underline', 'strikethrough',  'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist','fontfamily', 'fontsize','justifyleft', 'justifycenter', 'justifyright', 'justifyjustify','imagecenter', '|', 'insertimage', 'emotion', 'insertvideo', 'attachment', 'gmap', 'highlightcode','pagebreak', '|','horizontal', 'date', 'time', 'spechars','inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
]],
autoHeightEnabled:false,
wordCount:false,
minFrameHeight:500
});
editor.render("myEditor");
</script>


widgets 已经编写完毕。

步骤6:应用到form中:

class PostForm(forms.ModelForm):
from rte.ueditor.widgets import Ueditor

myContent = forms.CharField(widget=Ueditor())


到此就结束了。

本文出自 “YEELONⒼ ” 博客,请务必保留此出处http://yeelone.blog.51cto.com/1476571/922097
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: