Search code examples
djangodjango-formsdjango-tinymce

tinymce widget usage in django template


I created a model

class Post(models.Model):
    title = models.TextField()
    body = models.TextField()

and created forms.py as

class PostForm(forms.ModelForm):
    class Meta:
        model  = Post
        fields = ('title', 'body',)

I have added tinymce and it works in admin but doesn't render it in template. I tried to override the form through a variant of forms.py as

class PostForm(forms.ModelForm):

    title = forms.TextField(widget=TinyMCE(attrs={'cols': 100, 'rows': 10})

    class Meta:
        model  = Post
        fields = ('title', 'body',)

but it doesn't work . Thanks in advance


Solution

  • 1.) Add the Media class to your form:

    class PostForm(forms.ModelForm):
    
        class Meta:
            model = Post
            fields = ('title', 'body',)
    
        class Media:
            js = ('/site_media/static/tiny_mce/tinymce.min.js',)
    

    2.) Add the following to the html file which should display the editor:

    {{ form.media }}
    <script type="text/javascript" src="{% url "tinymce-js" "tinymce" %}"></script>
    

    3.) Add the following url entry to your project urls.py:

    url(r'^tinymce/', include('tinymce.urls')),
    

    4.) In your model declare your tinymce editor fields as TextFields. In your case if you only want to display the editor for your body field, write your model in the following way:

    class Post(models.Model):
    
        title = models.CharField()
        body = models.TextField()