django图片上传步骤


发布时间:2019-02-15 13:08    作者: 晖哥哥   已过去:4 年,1 月   阅读总量:3497 已被赞:1


django有内置的富文本编辑器django-ckeditor,所有直接安装插件导入使用就可以了,详细步骤如下:

安装django-ckeditor

pip install django-ckeditor

安装Pillow

Pillow是python的一个图像处理库,django-ckeditor需要依赖该库。最简单的安装方法,当然是使用pip,假设你装过pip,可以直接运行以下命令安装:

pip install pillow

配置你的django

要使安装好的django-ckeditor生效,你需要对你的django应用进行一系列配置。

1、在你的settings.py文件中,将ckeditor(富文本)、ckeditor_uploader(富文本里上传文件)添加到INATALLED_APPS中。

2、在你的settings.py文件中,添加CKEDITOR_UPLOAD_PATH配置项。例如,我的是:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')     #设置静态文件路径为主目录下的media文件夹
MEDIA_URL = '/media/'#url映射
#富文本图片存放路径
CKEDITOR_UPLOAD_PATH = "article_images"
#富文本选项(非必要)
CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': (
         ['div','Source','-','Save','NewPage','Preview','-','Templates'],
         ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print','SpellChecker','Scayt'],
         ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
         ['Form','Checkbox','Radio','TextField','Textarea','Select','Button', 'ImageButton','HiddenField'],
         ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
         ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
         ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
         ['Link','Unlink','Anchor'],
         ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
         ['Styles','Format','Font','FontSize'],
         ['TextColor','BGColor'],
         ['Maximize','ShowBlocks','-','About', 'pbckcode'],
      ),
   }
}

需要指出的是:在开发阶段,这样设置settings.py已经足够了。但是,到了正式部署你的应用时,你需要设置好STATIC_ROOT和STATIC_URL,并运行manage.py collectstatic命令,该命令会将ckeditor相关的静态资源拷贝到你的工程下。

在总urls.py中增加ck的url配置:

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(urls)),
    path('blog/', include(urls)),
    path('ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

如何应用ckeditor

django-ckeditor提供了两个类:RichTextField和CKEditorWidget,分别用于模型和表单。内容型网站通常在后台会有一个文章发布和编辑的界面,如果你想让该界面拥有一个富文本编辑器,只需按如下方式定义你的django模型:

from django.db import models
from ckeditor.fields import RichTextField

class Article(models.Model):
    content = RichTextField('文章标题')

注意,如果要使用上传图片功能,就要这样:

from ckeditor_uploader.fields import RichTextUploadingField #导入富文本模块

class Article(models.Model):

   content = RichTextUploadingField('文章标题')

 

如何在前端显示ck输入的内容
前端要显示ck输入的内容时,在需要使用的页面头部引入:
<script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script>
<script type="text/javascript" src="{% static 'ckeditor/ckeditor/ckeditor.js'%}"></script>
并且只能通过表单渲染过去,在表单渲染的时候,这样设置
forms.py
from django import forms
from ckeditor.widgets import CKEditorWidget

class CommentForm(forms.Form):
    text = forms.CharField(min_length=3,max_length=200,widget=CKEditorWidget())
    post_title = forms.CharField()
    comment_author=forms.CharField()

一些表单默认字段填充的值,可以在实例化渲染表但是传过去:

comment_Form = CommentForm(initial={'comment_author':request.user.id,'post_title':post_id})
前后两端因为需求不同,对富文本功能也不同,可以给配置取名字,再指定分别配置:
from django import forms
from ckeditor.widgets import CKEditorWidget

class CommentForm(forms.Form):
    text = forms.CharField(min_length=3,max_length=200,widget=CKEditorWidget(config_name='qianduan_ckeditor',attrs={'class':'form-control'}))
    post_title = forms.CharField(widget=forms.HiddenInput())
    comment_author=forms.CharField(widget=forms.HiddenInput())

settings.py

#富文本选项(非必要)
CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': (
         ['div','Source','-','Save','NewPage','Preview','-','Templates'],
         ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print','SpellChecker','Scayt'],
         ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
         ['Form','Checkbox','Radio','TextField','Textarea','Select','Button', 'ImageButton','HiddenField'],
         ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
         ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
         ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
         ['Link','Unlink','Anchor'],
         ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
         ['Styles','Format','Font','FontSize'],
         ['TextColor','BGColor'],
         ['Maximize','ShowBlocks','-','About', 'pbckcode'],
      ),
   },
    'qianduan_ckeditor':{}  #什么配置都不写,就取个名字,默认会使用默认配置
}

光这样你会发现,显示出来的时候是原始的包含各种html标签等符号的内容,此时在变量中增加safe过滤即可,如:{{ content | safe }}。

点赞

1




登陆后方可评论