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

问题描述 投票:0回答:1

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

editLecture HTML将讲座ID传递给editLecture视图

...
<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视图将讲座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的新手,所以如果我错过了一些明显的或者我的代码没有遵循约定,我会道歉;据我所知,我在本网站上看到的任何其他问题都没有解决这个错误。

django python-3.x tinymce django-tinymce
1个回答
2
投票

您将窗口小部件设置为Field对象,该对象本身具有窗口小部件。不要那样做。

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

但是,这不是执行此操作的方法。在从视图初始化表单时,您应该传递instance属性,然后您根本不需要处理初始数据。

lecture = Lecture.objects.get(id=id_string)
lecture_form = LectureUpdateForm(instance=lecture)
© www.soinside.com 2019 - 2024. All rights reserved.