获取全局配置 (上下文渲染器)
# settings.py
SITE_NAME = 'My Blog'
'context_processors': ['blog.views.global_settings']
#
# blog.views.py
def global_settings():
return {'site_name': settings.SITE_NAME}
#
# index.html
{{ site_name }}
扩展 User
# models.py
from django.contrib.auth.models import AbstractUser
class User(AbstracUser):
qq
mobile
#
# settings.py
AUTH_USER_MODEL = 'blog.User'
富文本编辑器
# admin.py
class Media:
js = (' ../kindeditor-min.js', '../lang/zh_CN.js', 'config.js') // config.js 是自己创建的
#
# config.js
KindEditor.ready(function(K) {
window.editor = K.create('textarea[name=content]', {width: '500px', height: '200px'});
});
上传文件
# 开启
# settings.py
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
#
# urls.py
url(r'^uploads/(?P<path>.*)$,'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, })
# models.py
avatar = models.ImageField(upload_to='avatar/%Y/%m') // 求测试没有配置情况
集成 kindeditor
# 配置 url
url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image')
# 配置 config.js
uploadJson: '/admin/upload/kindeditor'
# 创建 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 = 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}