*用户头像上传
用户模型
class User(AbstractUser):
avatar = models.ImageField(upload_to='avatar/%Y/%m', default='avatar/defaut.png', max_length=200,
blank=True, null=True, verbose_name='用户头像')
qq = models.CharField(max_length=20, blank=True, null=True, unique=True, verbose_name='QQ号')
mobile = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号')
class Meta:
verbose_name = '用户'
verbose_name_plural = verbose_name
ordering = ['-id']
def __str__(self):
return self.username
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.conf.urls import include, url
from django.contrib import admin
from blog.views import *
from django.conf import settings ##
from django.conf.urls.static import static ##
urlpatterns = [
# url(r'^uploads/(?P.*)$',
# 'django.views.static.serve',
# {'document_root':settings.MEDIA_ROOT,}
# ),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', index , name='index'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ##
------------------------
*富文本编辑器中的图像上传
1.新建blog.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 += '/%d/%d/' % (today.year, today.month)
path = settings.MEDIA_ROOT + dir_name
if not os.path.exists(path):
os.makedirs(path)
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}
...
from blog.upload import upload_image
urlpatterns = [
...
url(r'^admin/upload/(?P[^/]+)$', upload_image, name='upload_image'),
]
KindEditor.ready(function(K) {
window.editor = K.create(
'textarea[name="content"]',
{
uploadJson:'/admin/upload/kindeditor',
}
);
});