I am trying to display the RichTextField in a Django Template. In the Admin Panel it works but not in the template. My Template called create.html:
{% block main %}
<div class="blocker" style="height: 100px;"></div>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Absenden</button>
</form>
{% endblock %}
Forms.py:
class Create(forms.ModelForm):
content = RichTextField()
title = forms.CharField(label='title', max_length=100)
class Meta:
model = Post
fields = ['title', 'content']
Views.py
def create(request):
if request.method == 'POST':
form = Create(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
content = form.cleaned_data['content']
Post(title=title, content=content).save()
return redirect("../blog")
else:
form = Create()
return render(request, 'create.html', {'form': form})
I tried different things in the forms.
Assuming, that you have already installed the package using pip install django-ckeditor
and also included it in INSTALLED_APPS
list in your settings.py
file.
Try to use {{ form.media }}
tag which include the necessary scripts and stylesheets, so in the template:
{% block main %}
<div class="blocker" style="height: 100px;"></div>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
{{ form.media }}
<button type="submit">Absenden</button>
</form>
{% endblock %}
In your forms.py
, import the CKEditorWidget
and use it to override the default widget for the content field, like so:
from ckeditor.widgets import CKEditorWidget
class Create(forms.ModelForm):
content = forms.CharField(widget=CKEditorWidget())
title = forms.CharField(label='title', max_length=100)
class Meta:
model = Post
fields = ['title', 'content']