django - 将初始值传递给使用 TinyMCE 小部件的表单 CharField 时,“CharField”对象没有属性 'is_hidden'

标签 django python-3.x tinymce django-tinymce

我正在建立一个网站,用户可以在其中创建具有风格化讲座文本的“讲座”。在创建讲座时填写lecture_text字段时应用的TinyMCE插件可以促进这种风格。创建讲座效果很好,但我希望这个风格化文本已经位于讲座更新表单的讲座文本区域中。据我了解,我可以使用 initial 参数设置 TinyMCE CharField 的默认内容。这是我现在的代码:

editLecture HTML 将讲座 ID 传递到 editLecture View

...
<form method="post" action="{% url 'openvlab:editLecture' lecture_id %}">
    {% csrf_token %}
    {{ lecture_form.as_p }}
    <script src="https://cloud.tinymce.com/5/tinymce.min.js?apiKey=re1omq7fkhbmtyijhb3xvx4cfhyl3op33zggwlqkmbt5swvp"></script>
    <script>tinymce.init({ selector:'textarea' });</script>
    <button type="submit">Save changes</button>
</form>

editLecture View 将讲座 ID 传递到讲座更新表单

def editLecture(request,id_string):
...
    lecture_form = LectureUpdateForm(lecture_id=id_string)
...

讲座更新表

class LectureUpdateForm(forms.ModelForm):
    def __init__(self,*args,**kwargs):
        lecture_id=kwargs.pop("lecture_id")
        lecture = Lecture.objects.get(id__exact=lecture_id)
        super(LectureUpdateForm, self).__init__(*args,**kwargs)
        self.fields['lecture_text'].widget = forms.CharField(
                 widget=TinyMCEWidget(
                     attrs={'required': False, 'cols': 30, 'rows': 10},
                     ),  
                 initial=lecture.lecture_text # this is where I try to define the initial content of the editor
                 )

    class Meta:
        model = Lecture
        fields = ['lecture_title', 'lecture_description', 'lecture_text']

但是,当尝试访问讲座编辑页面时,我收到 AttributeError: 'CharField' 对象没有属性 'is_hidden'。 (如果您需要更详细的回溯,请告诉我,我会提供。)

我对 Django 相当陌生,所以如果我错过了一些明显的东西或者我的代码不遵循约定,我深表歉意;据我所知,我在此网站上看到的任何其他问题都没有解决此错误。

最佳答案

您正在将小部件设置为 Field 对象,该对象本身也有一个小部件。不要这样做。

self.fields['lecture_text'] = forms.CharField(...)
#                          ^

但是,这不是执行此操作的方法。从 View 初始化表单时,您应该传递 instance 属性,这样您就根本不需要搞乱初始数据。

lecture = Lecture.objects.get(id=id_string)
lecture_form = LectureUpdateForm(instance=lecture)

关于django - 将初始值传递给使用 TinyMCE 小部件的表单 CharField 时,“CharField”对象没有属性 'is_hidden',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55460677/

相关文章:

python - 是否可以在 Django 管理面板中过滤外键的选择?

javascript - Django - 使用 Javascript 将 ID 传递到 url 模板标记中

python-3.x - 发现 stdout 输出的来源

python - 错误哈希+盐密码

extjs4 - 将tinyMCE 4集成到extJS 4中

python - 如何更改 PyCharm 中的 django 版本?

python - 测试用户模型是否有密码的正确方法

python - conda 安装的软件包不适用于 jupyter

javascript - 如何集成TinyMCE按钮和传递变量

Plone 站点的 TinyMCE-对话框未翻译