Django-summernote富文本
1、设置MEDIA_ROOT和MEDIA_URL
2、设置media的url
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
3、设置图片上传路径
def uploaded_filepath(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
today = datetime.now().strftime('%Y-%m-%d')
# upload path is MEDIA_ROOT/summernote/today/filename
return os.path.join('summernote/', today, filename)
4、配置SummerNote
SUMMERNOTE_CONFIG = {
'width': '100%',
'lang': 'zh-CN',
'iframe': True,
'attachment_upload_to': uploaded_filepath,
'attachment_require_authentication': True,
'internal_js': (
'/static/django_summernote/lang/summernote-zh-CN.min.js',
),
}
5、在ModelForm中使用
# Summer noteWidget固定大小 Summer noteInplaceWidget 自由大小
# 使用Summer noteInplaceWidget 时会有图片无法上传的bug
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
# 博客表单
class ArticleForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ArticleForm, self).__init__(*args, **kwargs)
self.fields['category'].widget.attrs.update({'class': 'form-control'})
class Meta:
model = Article
fields = '__all__'
widgets = {
'content': SummernoteWidget(),
}
6、在admin中使用
TextField类型对应的字段在admin中会自动渲染成为富文本编辑框。
7、html中调用
一定要调用form.media来加载django-summernote系统的静态文件(css、js、images等)
<form class="form" enctype="multipart/form-data" action="{% url 'article_create' %}" method="post">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<input class="btn btn-raised btn-info" style="float:right;" type="submit" value="发布博客" />
</form>
8、在ModelForm中使用
使用SummernoteInplaceWidget模式会出现图片无法上传的bug,提示403 csrf_token验证失败被拒绝,解决方法为将django_summernote/templates/django_summernote/widget_inplace.html的第八行由var csrftoken = getCookie('{{ CSRF_COOKIE_NAME }}');
改为 var csrftoken = getCookie('csrftoken');
即可正确获取到正确的scrf_token用于图片上传。
常见问题:
1 form中Summernoteinplace无法被正常加载,解决方法为在templates的form中加入{{ form.media }}。