我正在尝试在 Django 模板中显示 RichTextField。它在管理面板中有效,但在模板中无效。我的模板名为 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 %}
表格.py:
class Create(forms.ModelForm):
content = RichTextField()
title = forms.CharField(label='title', max_length=100)
class Meta:
model = Post
fields = ['title', 'content']
视图.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})
我在表格中尝试了不同的东西。
假设您已经使用安装包pip install django-ckeditor
并将其包含在文件INSTALLED_APPS
列表中settings.py
。
尝试使用{{ form.media }}
包含必要脚本和样式表的标签,因此在模板中:
{% 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 %}
在您的 中forms.py
,导入CKEditorWidget
并使用它来覆盖内容字段的默认小部件,如下所示:
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']
你也可以分享你的Post模型,因为RichTextField模型字段不是表单字段吗?