djangotinymcedjango-tinymce

Form stopped saving to database after TextField was changed to HTMLField


I had a working input form for my model, which included a TextField called 'Opis'. The instances of the model were successfully saved to the database. However, I wanted to give my users more options when writing -- and storing -- that particular bit of text. So I installed TinyMCE, changed the TextField to HTMLField and discovered that this, together with putting

<head> {{ form.media }} </head> 

at the beginning of my template was enough for the input field to be rendered as a TinyMCE widget. That is, I kept my old ModelForm, and what it displayed changed, which I thought was nice and convenient. However, when the user submits the form, nothing happens -- it seems the form is valid, but the database is not updated.

In my models.py:

from tinymce.models import HTMLField

class Kurs(models.Model):
   [skipping...]
   opis = HTMLField()
   [skipping the rest]

in my forms.py:

class KursForm(ModelForm):
    class Meta:
        model = Kurs
        fields = "__all__"      

in my views.py:

def createcourse(request):
    if request.method=='POST':
        form = KursForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/polls/usersite')
    else:
        form = KursForm()

    return render(request, 'polls/createcourse.html', {"form" : form})

and in the createcourse.html:

<head>{{ form.media }}</head>

<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>

Clicking 'Submit' results in no observable effect. Everything worked perfectly until I changed the TextField to a HTMLField. What am I doing wrong?

edit: it seems there is a similar issue raised about TinyMCE, but I want to report that in my case editing the form in forms.py to

class KursForm(ModelForm):
    opis = forms.CharField(widget=TinyMCE(attrs={'required': False, 'cols': 30, 'rows': 10}))
    class Meta:
        model = Kurs
        fields = "__all__"      

didn't help.


Solution

  • Alright, it turns out that this indeed is an issue with TinyMCE. ClaudeP was kind enough to help me in this thread. To sum up, what I have now and what is doing the job is the following:

    -- subclassing the widget:

    class TinyMCEWidget(TinyMCE):
        def use_required_attribute(self, *args):
            return False
    

    -- having modified the form to what follows (I guess this might be optional):

    class KursForm(ModelForm):
        opis = forms.CharField(widget=TinyMCEWidget(attrs={'required': False, 'cols': 30, 'rows': 10}))
        class Meta:
            model = Kurs
        fields = "__all__"