1. 在项目目录下新建一个 ‘uploads’文件夹以保存上传的文件
  2. 配置setting.py文件
    MEDIA_URL = '/uploads/'
    
    MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')  #设置上传的绝对路径
  3. 配置urls.py文件,设置路由
    from django.conf.urls import url,include
    from django.contrib import admin
    from django.conf import settings urlpatterns = [
    url(r'^uploads/(?P<path>.*)$',\
    'django.views.static.serve', \
    {'document_root': settings.MEDIA_ROOT,}),
    url(r'^admin/', admin.site.urls),
    url(r'^todolist/',include('todolist.urls')),
    ]
  4. 为富文本编辑器设置上传文件
    1. 在APP目录下创建配置文件‘upload.py’

      # -*- coding: utf-8 -*-
      from django.http import HttpResponse
      from django.conf import settings
      from django.views.decorators.csrf import csrf_exempt
      import os
      import uuid
      import json
      import datetime as dt @csrf_exempt
      def upload_image(request, dir_name):
      ##################
      # kindeditor图片上传返回数据格式说明:
      # {"error": 1, "message": "出错信息"}
      # {"error": 0, "url": "图片地址"}
      ##################
      result = {"error": 1, "message": "上传出错"}
      files = request.FILES.get("imgFile", None)
      if files:
      result =image_upload(files, dir_name)
      return HttpResponse(json.dumps(result), content_type="application/json") #目录创建
      def upload_generation_dir(dir_name):
      today = dt.datetime.today()
      dir_name = dir_name + '/%d/%d/' %(today.year,today.month)
      if not os.path.exists(settings.MEDIA_ROOT + dir_name):
      os.makedirs(settings.MEDIA_ROOT + dir_name)
      return dir_name # 图片上传
      def image_upload(files, dir_name):
      #允许上传文件类型
      allow_suffix =['jpg', 'png', 'jpeg', 'gif', 'bmp']
      file_suffix = files.name.split(".")[-1]
      if file_suffix not in allow_suffix:
      return {"error": 1, "message": "图片格式不正确"}
      relative_path_file = upload_generation_dir(dir_name)
      path=os.path.join(settings.MEDIA_ROOT, relative_path_file)
      if not os.path.exists(path): #如果目录不存在创建目录
      os.makedirs(path)
      file_name=str(uuid.uuid1())+"."+file_suffix
      path_file=os.path.join(path, file_name)
      file_url = settings.MEDIA_URL + relative_path_file + file_name
      open(path_file, 'wb').write(files.file.read())
      return {"error": 0, "url": file_url}
    2. 为富文本编辑器设置路由。urls.py
      from django.conf.urls import url
      from django.contrib import admin
      from blog.views import index
      from django.conf import settings
      from blog.upload import upload_image urlpatterns = [
      url(r'^uploads/(?P<path>.*)$',\
      'django.views.static.serve',\
      {'document_root': settings.MEDIA_ROOT,}),
      url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),
      url(r'^admin/', admin.site.urls),
      url(r'^$', index, name='index')
      ]
    3. 配置KindEditor,在config.js文件中
      KindEditor.ready(function(K) {
      K.create('textarea[name="content"]', {
      width : "800px",
      height : "200px",
      uploadJson: '/admin/upload/kindeditor',
      });
      });

万里长征第二步——django个人博客(第七步 ——上传文件)的更多相关文章

  1. 万里长征第二步——django个人博客(第一步 ——创建主页)

    运行命令行工具,输入:pip install virtualenv  --安装virtualenv库. virtualenv blog_project_venv ——使用virtualenv创建一个虚 ...

  2. 万里长征第二步——django个人博客(第三步 —— 设置一些全局变量)

    可以将一些全局变量设置在settingg.py里 #网站的基本信息配置 SITE_NAME = 'John的个人博客' SITE_DESC = '专注学习Python开发,欢迎和大家交流' WEIBO ...

  3. django中博客后台将图片上传作为用户头像

    添加上传目录 # 如果不添加上传目录,仍然可以上传成功,默认为project目录,如果models.py定义了upload_to="目录名称",则会上传到"project ...

  4. 万里长征第二步——django个人博客(第五步 ——配置后台admin)

    在urls.py文件中配置admin路径 from django.conf.urls import url from django.contrib import admin from blog.vie ...

  5. 万里长征第二步——django个人博客(第四步 ——创建数据库)

    在models.py内设置数据库模型 # -*- coding=utf-8 -*- from __future__ import unicode_literals from django.db imp ...

  6. 万里长征第二步——django个人博客(第二步 ——日志记录器)

    定义日志记录器 可以在setting.py里设置日志记录器 # 自定义日志输出信息 LOGGING = { 'version': 1, 'disable_existing_loggers': True ...

  7. 万里长征第二步——django个人博客(第六步 ——添加富文本编辑器)

    下载kindeditor 在admin.py文件中配置链接 class Media: js = ( '/static/js/kindeditor-4.1.10/kindeditor-min.js', ...

  8. Django 系列博客(七)

    Django 系列博客(七) 前言 本篇博客介绍 Django 中的视图层中的相关参数,HttpRequest 对象.HttpResponse 对象.JsonResponse,以及视图层的两种响应方式 ...

  9. 基于Ubuntu Server 16.04 LTS版本安装和部署Django之(三):设置上传文件夹权限(这里测试用完全共享)

    基于Ubuntu Server 16.04 LTS版本安装和部署Django之(一):安装Python3-pip和Django 基于Ubuntu Server 16.04 LTS版本安装和部署Djan ...

随机推荐

  1. idea+spring+springmvc+mybatis+mybatis+maven

    使用SSM(Spring,SpringMVC和Mybatis) 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johns ...

  2. C# 笔记——数据类型

    一张图读懂C#数据类型:

  3. 机器学习方法:回归(三):最小角回归Least Angle Regression(LARS),forward stagewise selection

    欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld. 希望与志同道合的朋友一起交流,我刚刚设立了了一个技术交流QQ群:433250724,欢迎对算法.技术.应用感 ...

  4. Sort List——经典(链表中的归并排序)

    Sort a linked list in O(n log n) time using constant space complexity.    对一个链表进行排序,且时间复杂度要求为 O(n lo ...

  5. SEO如何写好文章标题

    近一半网民只看标题不点内容,许多网站有个标题和内容摘要,而这个摘要基本概括了整篇新闻的大致内容,所以的互联网信息泛滥的今天,看标题看摘要成了最快阅读新闻资讯的一种有效方式. 如何写好标题?我一直愁这事 ...

  6. lr_Analysis Options选项介绍

  7. 部署centos6

    挂载镜像和导入镜像 mount /dev/cdrom /media ll /media/ cobbler import --path=/media --name=centos6.5--arch=x86 ...

  8. ubuntu16.04 安装composer和 laravel

    一.安装composer $ sudo apt-get update $ sudo apt-get install wget 下载composer.phar $ wget https://getcom ...

  9. linux在命令执行过程中ctrl +z 后[1]+ Stopped

    进程挂起 stopped 代表有进程挂起 [1]是id号 可以通过Linux命令:jobs 查看挂起进程 fg 1 把任务1放到前台 bg 1 把任务1放到后台

  10. 捕获浏览器的前进、后退事件 window.onhashchange 并区别于点击链接

    <html> <head> <meta http-equiv="content-type" content="text/html;chars ...