Editor TinyMCE no Django admin
11 de fevereiro de 2010Primeiramente, TinyMCE é um editor WYSIWYG (“O que você vê é o que você obtem”) mais popular em todo o mundo. É usado em grandes CMS como Wordpress e Joomla. Aqui vamos implementar o TinyMCE no painel de administração do Django.
Preview

Screencast (vídeo tutorial)
Vamos por etapas
- Fazer o download do TinyMCE
- Criar estrutura de pastas do template
- Configurar o TEMPLATE_DIRS no settings.py do seu projeto (exemplo abaixo)
- Editar o urls.py
- Editar o admin.py
- Criar arquivo de configuração do TinyMCE
2. Estrutura
A estrutura de pastas é algo como:
- projeto
- app
- templates
- css
- js
- tinymce

Coloque a pasta do tinymce dentro de projeto > templates > js, como na figura acima.
3. TEMPLATE_DIRS (settings.py)
Edite o settings.py e edite/inclua essas linhas:
1 2 3 4 5 | import os.path TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) |
4. Servindo os arquivos estáticos
Abra o arquivo urls.py (na raiz do projeto) e adicione a linha 3 como abaixo:
1 2 3 4 5 | urlpatterns = patterns('', ... (r'^js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'templates/js'}), ... ) |
Assim, quando abrimos http://127.0.0.1:8000/js/textareas.js, por exemplo, o arquivo /projeto/templates/js/textareas.js é requisitado.
5. Agora o admin.py
Se você está usando o admin do django, deve existir o arquivo admin.py dentro da pasta da aplicação. Se não existir, dê uma olhada na documentação sobre o admin.
Edite o admin.py de acordo com o seu projeto. No meu exemplo está assim:
1 2 3 4 5 6 7 8 | from django.contrib import admin from weblog.blog.models import Post class PostAdmin(admin.ModelAdmin): class Media: js = ('/js/tiny_mce/tiny_mce.js', '/js/textareas.js') admin.site.register(Post, PostAdmin) |
6. E o textareas.js
Já está acabando, falta dizer à engine do TinyMCE qual o tema, tamanho e botões nossas textareas vão ter. Conforme colocamos no admin.py, crie o arquivo textareas.js na pasta templates > js. O meu está assim:
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 | tinyMCE.init({ // General options mode : "textareas", theme : "advanced", plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave", // Theme options theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,fullscreen,code", theme_advanced_buttons2 : "cut,copy,paste,pastetext,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,|,insertdate,inserttime,preview,|,forecolor,backcolor", theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : true, // Example content CSS (should be your site CSS) //content_css : "/css/style.css", template_external_list_url : "lists/template_list.js", external_link_list_url : "lists/link_list.js", external_image_list_url : "lists/image_list.js", media_external_list_url : "lists/media_list.js", // Style formats style_formats : [ {title : 'Bold text', inline : 'strong'}, {title : 'Red text', inline : 'span', styles : {color : '#ff0000'}}, {title : 'Help', inline : 'strong', classes : 'help'}, {title : 'Table styles'}, {title : 'Table row 1', selector : 'tr', classes : 'tablerow'} ], width: '700', height: '400' }); |
No arquivo baixado você encontra exemplos do tema advanced e do simple.
Mais informações: AddWYSIWYGEditor (no site oficial do Django)
Descer
Ir para o topo
Olá, tudo bom? usei seu artigo e funcionou, muito tranquilo, mas só funcionou local, na minha máquina, quando hospedei na web, parou de funcionar, e é estranho pq eu so dei um svn updade na pasta web, ou seja, está identico ao local, por um acaso vc sabe de algum pré-requisito que tem que ter para isso funcionar? acho que só pode ser isso.
@Olavo,
Estranho, deveria funcionar normalmente. Tente usar a extensão Firebug pra debuggar o javascript e verifique se, no site já na web, os arquivos do TinyMCE estão sendo carregados (eu uso a extensão Web Developer também).
hello, i follow your steps successfully to embed tinymce
in admin.But when i save message, an error message”This field is required.”appears!!
@yyt
What is the required field: textarea, title, slug or another?
Please, show me your models.py.
Thank you!
from django.db import models
from django.contrib import admin
import re
from tinymce import models as tinymce_models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=100)
date_created = models.DateTimeField()
date_modified = models.DateTimeField(auto_now=True)
tags = models.CharField(max_length=200)
body = tinymce_models.HTMLField()
def get_tag_list(self):
return re.split(” “, self.tags)
def __unicode__(self):
return self.title
class Meta:
ordering = (“-date_created”,)
i fill the content in body, but after i click button “save”, the body is empty and comes the error of “This field is required.”
the version of django is 1.2
the version of django-tinymce is 1.5
the version of tinymce is tinymce is 3.3.7
i am looking forward your reply as soon as possible,
thank u very much!!!
@yyt
This tutorial don’t use the django-tinymce app. It’s the reason for your project run incorrectly. My text field is a models.TextField() and following the tutorial steps, every text field of the django admin will use the tinymce.
I’ll make a screencast of this post. Thank you.
i modfiy the error,but the body of blog is html,for example“dsfafssdssasa “。
i think u must write some code in base.html.
@yyt
http://docs.djangoproject.com/en/dev/topics/templates/
This will be escaped: {{ data }} This will not be escaped: {{ data|safe }}I made a screencast at Vimeo.com: TinyMCE (editor WYSIWYG) in Django Admin
Luis, como faço para colocar no idioma pt-br?
@salsotto, baixe o pacote pt aqui: http://tinymce.moxiecode.com/download_i18n.php
Depois extraia as 3 pastas do arquivo zip (themes, plugins, langs) na raiz da pasta do tinymce (se seguiu o tutorial, em /templates/js/tiny_mce). Edite o textareas.js, acrescentando o language:
Espero ter ajudado. Um abraço.