问题描述
我已经安装了 CKeditor 并将其应用到 models.py。我运行迁移并将其迁移到数据库。我试图通过转到管理页面来测试它。我可以看到 CKeditor 正在显示,但是当我使用 CreateView 将其渲染到我的 模板 时,它没有显示。
Models.py
from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField
class Content(models.Model):
title = models.CharField(max_length=250)
content = RichTextField(blank=True,null=True)
date = models.DateField(auto_Now_add=True)
website = models.URLField()
github = models.URLField()
image = models.ImageField(upload_to=get_image_filename,verbose_name='Image')
Forms.py
class ContentForm(forms.ModelForm):
class Meta:
model = Content
fields = [
'title','content','website','github','image',]
Views.py
class CreateContentView(CreateView):
form_class = ContentForm
template_name = 'appOne/create_content.html'
模板
<form method="POST">{% csrf_token %}
{{ form.text | safe }}
{{ form.media }}
<input type="submit" value="Save">
</form>
奇怪的是,在管理页面中,CKeditor 工作得很好,但是当我将它传递给模板时,工具栏和菜单栏没有显示。
解决方法
从他们的 github https://github.com/django-ckeditor/django-ckeditor#outside-of-django-admin 你的表单中的代码应该看起来像
from ckeditor.widgets import CKEditorWidget
class ContentForm(forms.ModelForm):
content = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Content
fields = [
'title','content','website','github','image',]
和你的模板
<form>
{% csrf_token %}
{{ form.text | safe }}
{{ myform.media }}
{{ myform.as_p }}
<input type="submit" value="Save">
</form>
,
在 forms.py 中试试这个:
from ckeditor.widgets import CKEditorWidget
class ContentForm(forms.ModelForm):
content = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Content
fields = '__all__'
在模板中:
<form>
{{ form.media }}
{{ form.as_p }}
<input type="submit"/>
</form>