2

我目前在 Django 管理界面中使用 TinyMCE 编辑器时遇到问题。当在两个特定的 TinyMCE 字段中输入文本并按保存时,将返回表单,两个字段均为空,标记为红色并标有“此字段为必填项”标签:

在此处输入图像描述

这种行为很奇怪,因为我在不同的模型中实现了各种 TinyMCE 编辑器,它们运行良好。我应该澄清一下,我希望这两个字段都是强制性的。问题是输入的文本被丢弃,返回的表单两个字段都为空。以下是所有相关代码:

companycms/新闻/models.py

from django.db import models
from tinymce import models  as tinymce_models

class Article(models.Model):
    headline = models.CharField(max_length=200)
    content = tinymce_models.HTMLField()
    about = tinymce_models.HTMLField()
    pub_date = models.DateTimeField('date published')
    url = models.CharField(max_length=200)

companycms/新闻/forms.py

from django import forms
from django.db.models import get_model
from django.contrib.auth.models import User
from companycms.widgets import AdvancedEditor
from news.models import Article
from django.db import models

class ArticleModelAdminForm(forms.ModelForm):
    headline = forms.CharField(max_length=200)
    content = forms.CharField(widget=AdvancedEditor())
    about = forms.CharField(widget=AdvancedEditor())
    pub_date = models.DateTimeField('date published')
    url = forms.CharField(max_length=200)

    class Meta:
         model = Article

companycms/新闻/admin.py

from django.contrib import admin
from news.models import Article
from news.forms import ArticleModelAdminForm

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('headline', 'pub_date',)
    form = ArticleModelAdminForm

admin.site.register(Article, ArticleAdmin)

companycms/companycms/widgets.py

from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe

class AdvancedEditor(forms.Textarea):
    class Media:
        js = ('/static/tiny_mce/tiny_mce.js',)

    def __init__(self, language=None, attrs=None):
        self.language = language or settings.LANGUAGE_CODE[:2]
        self.attrs = {'class': 'advancededitor'}
        if attrs: self.attrs.update(attrs)
        super(AdvancedEditor, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        rendered = super(AdvancedEditor, self).render(name, value, attrs)
        return rendered + mark_safe(u'''
        <script type="text/javascript">
        tinyMCE.init({
            mode: "textareas",
            theme: "advanced",
            plugins: "advhr,table,emotions,media,insertdatetime,directionality",
            theme_advanced_toolbar_align: "left",
            theme_advanced_toolbar_location: "top",             
    theme_advanced_buttons1:"bold,italic,underline,strikethrough,sub,sup,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,formatselect,fontselect,fontsizeselect,forecolor",
theme_advanced_buttons2:"bullist,numlist,outdent,indent,ltr,rtl,separator,link,unlink,anchor,image,separator,table,insertdate,inserttime,advhr,emotions,media,charmap,separator,undo,redo",
            theme_advanced_buttons3_add:"forecolor,backcolor",


theme_advanced_font_sizes:"170%,10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px,32px,48px",
            height: "350px",
            width: "653px"
        });
        </script>''')

检查 JavaScript 控制台后,没有返回任何错误,我检查了其他管理页面,发现此错误没有出现在其他任何地方。

在此先感谢您的帮助。

4

4 回答 4

3

您应该blank=True在 companycms/news/models.py 中添加一个参数:

content = tinymce_models.HTMLField(blank=True)
于 2013-07-19T14:22:15.457 回答
1

是的,在 Django settings.py 中注释掉#'mode': 'textareas',一切都应该没问题!;)

TINYMCE_DEFAULT_CONFIG = {
    #'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_advanced_buttons1': '''bold, italic, underline, strikethrough, |,
                               justifyleft, justifycenter, justifyright,
                               justifyfull, fontselect, fontsizeselect,
                               fullscreen, code''',
    'theme_advanced_buttons2': '''bullist, numlist, |, outdent, indent,
                               blockquote, |, undo, redo, |, link, unlink, |,
                               forecolor, backcolor''',
    'theme_advanced_buttons3': '''tablecontrols, |, hr, sub, sup, |, charmap''',

    'theme_advanced_toolbar_location': "top",
    'theme_advanced_toolbar_align': "left",
    'theme_advanced_statusbar_location': "bottom",
    'theme_advanced_resizing': "true",

    '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': [
      {'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'
}
于 2013-11-25T15:04:58.413 回答
0

我猜您的自定义表单和自定义小部件给您带来了麻烦。前两件事。只是为了确定......你是否在settings.py中添加了tinymce?

INSTALLED_APPS = (
    ...
    'tinymce',
)

在 urlpatterns 中?

urlpatterns = patterns('',
    ...
    (r'^tinymce/', include('tinymce.urls')),
)

根据文档,您只需要 tinymce_models.HTMLField()。就像你做的那样。加载 TinyMCE 不需要所有其他代码(自定义表单和自定义小部件)。所以在 admin.py 中注释掉:

#form = ArticleModelAdminForm

现在手指交叉测试!工作正常吗?你可以重新打开它。

ArticleModelAdminForm 只需要您要调整的字段。删除标题、pub_date 和 url 字段。

不要在小部件中添加 js。但是创建一个新的js文件。删除渲染函数。添加js位置:

    class Media:
        js = ('/static/tiny_mce/tiny_mce.js', 
              '/static/tiny_mce/my_advanced_editor.js')

将类 Media 移动到 ModelAdmin。它在哪里加载一次,而不是每个文本区域。

希望能帮助到你!

编辑:

TinyMCE 在提交表单时丢失了数据,因为它被初始化了很多次。Django 没有收到 POST 数据并正确显示“此字段为必填项”。所以请确保初始化 TinyMCE 一次:

模型.py

class Article(models.Model):
    content = models.TextField() # Normal textfields (Don't load Tiny)
    about = models.TextField()

管理员.py

class ArticleAdmin(admin.ModelAdmin):
    class Media:
        js = ('/static/tiny_mce/tiny_mce.js', 
              '/path/to/my_advanced_editor.js') # Add js to head of admin.

my_advanced_editor.js

   tinyMCE.init({
        mode: "textareas",  // This applies Tiny to all textareas.
        theme: "advanced",          
        ...
    });

奖励:Django-TinyMCE 使得将 TinyMCE 应用于字段变得“容易”,但使用 TinyMCE 选择字段也很容易。使用精确模式:

mode : "exact",
elements : "id_content,id_about",

或取消选择:

    mode: "textareas",  // All textareas except...
editor_deselector : "NoEditor" // deselects class="NoEditor"

在最后一种情况下,您的 FormField 需要一个小部件:

    widget=forms.TextInput(attrs={'class':'NoEditor'})
于 2013-07-20T01:01:07.420 回答
0

目前我有同样的问题。我的解决方案是:

删除线mode: "textareas",

现在表单在提交后保存。:)

于 2013-11-03T16:29:45.857 回答