TinyMCE与Django:“此字段是必需的” [英] TinyMCE with Django: "This field is required"

查看:172
本文介绍了TinyMCE与Django:“此字段是必需的”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently having issues using the TinyMCE editor within the Django admin interface. When entering text into two particular TinyMCE fields and pressing save, the form is returned with both fields empty, flagged red and tagged with a "This field is required" label:

这个行为是奇怪的,因为我已经完成了不同型号的各种TinyMCE编辑器。我应该澄清,我希望这两个领域是强制性的。问题是输入的文本被丢弃,并且这两个字段都是空的返回的表单。以下是所有相关代码:

This behaviour is odd, as I have implemented various TinyMCE editors within different models which have worked perfectly. I should clarify that I wish for both fields to be mandatory. The problem is that the text entered is being discarded, and the form is returned with both fields empty. Here is all of the relevant code:

companycms / news / 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 / news / 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 /news/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控制台后,没有任何错误返回,我已经检查过其他管理页面,发现这个错误不会出现在其他地方。

Having checked the JavaScript console, there are no errors being returned, and I have checked other admin pages to find that this error doesn't appear anywhere else.

提前感谢您的帮助。

推荐答案

我想你的自定义窗体和自定义窗口小部件给你麻烦。前两件事只是为了确保...你在settings.py中添加了tinymce吗?

I guess that your custom form and custom widget give you trouble. First two things. Just to be sure... Did you add tinymce in settings.py?

INSTALLED_APPS = (
    ...
    'tinymce',
)

在urlpatterns?

And in urlpatterns?

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

根据文档,您需要的是tinymce_models .HTMLField()。和你一样所有其余的代码(自定义表单和自定义窗口小部件)不需要加载TinyMCE。所以在admin.py注释掉:

According to the documentation all you need is the tinymce_models.HTMLField(). Like you did. All the rest of your code (custom form and custom widget) is not necessary to load TinyMCE. So in admin.py comment out:

#form = ArticleModelAdminForm

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

Now fingers crossed and test! Works right? You can switch it back on.

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

ArticleModelAdminForm needs only the fields that you want to adjust. Remove the headline, pub_date and url fields.

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

Don't add the js in a widget. But create a new js file. Delete the render function. Add the js location:

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

将类Media移动到ModelAdmin 。加载一次,而不是每个textarea。

Move class Media to the ModelAdmin. Where it's loaded once, and not for each textarea.

希望它有帮助!

编辑:

TinyMCE由于初始化了许多次而丢失了提交表单的数据。 Django没有收到POST数据,并正确显示需要此字段。所以确保初始化TinyMCE一次:

TinyMCE looses data on submitting the form because it is initialized to many times. Django doesn't receive the POST data and correctly displays "This field is required". So make sure to initialize TinyMCE once:

models.py

models.py

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

admin.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

my_advanced_editor.js

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

奖金:Django-TinyMCE使TinyMCE应用于字段非常简单,但使用TinyMCE选择字段也很容易。使用模式确切:

Bonus: Django-TinyMCE makes it 'easy' to apply TinyMCE to fields but selecting fields with TinyMCE is also quite easy. With mode exact:

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

或取消选择:

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

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

In the last case your FormField needs a widget:

    widget=forms.TextInput(attrs={'class':'NoEditor'})

这篇关于TinyMCE与Django:“此字段是必需的”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆