djangopython-3.xtinymcedjango-tinymce

'CharField' object has no attribute 'is_hidden' when passing initial value to a form's CharField which uses a TinyMCE widget


I'm setting up a site where users can create "lectures" which have a stylized lecture text. The style is facilitated by the TinyMCE plugin applied when filling out the lecture_text field when creating a lecture. Creating the lecture works fine, but I'd like this stylized text to already be in the lecture text area of the lecture update form. To my understanding, I can set the default content of the TinyMCE CharField with the initial argument. Here is my code right now:

the editLecture HTML passes the lecture ID to the 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>

the editLecture view passes the lecture ID to the lecture update form

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

the lecture update form

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']

When trying to access the lecture editing page, however, I get an AttributeError: 'CharField' object has no attribute 'is_hidden'. (If you need a more detailed traceback, let me know and I will provide it.)

I'm fairly new to Django, so I apologize if I missed something obvious or my code isn't following conventions; to my knowledge, this error isn't addressed in any of the other questions I've seen on this site.


Solution

  • You're setting the widget to a Field object, which itself has a widget. Don't do that.

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

    However, this isn't the way to do any of this. You should be passing the instance attribute when initialising the form from the view, then you don't need to mess around with initial data at all.

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