1 知识点
- 配置使用Django Admin
- Admin后台管理Models
- 自定义ModelAdmin
- 定义ModelAdmin的媒体文件实现富文本编辑器
- 【ImageField】和富文本编辑器的图片上存功能
2 配置实用Django Admin
类似app的添加(这个步骤在创建项目的时候系统默认添加的)
【settings.py】
INSTALLED_APPS = [
'django.contrib.admin',
]
【urls.py】
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
3 Admin后台管理Models
创建超级用户
(env_py27_django_blog) D:\MaiZi_Edu\Dropbox\Maizi\Django_blog\django_blog>python manage.py createsuperuser
2017-01-02 12:43:01,736 [MainThread:13012] [django.db.backends:89] [utils:execute] [DEBUG]- (0.001) SET SQL_AUTO_IS_NULL = 0; args=None
Username: admin
2017-01-02 12:43:02,924 [MainThread:13012] [django.db.backends:89] [utils:execute] [DEBUG]- (0.000) SET SQL_AUTO_IS_NULL = 0; args=None
2017-01-02 12:43:02,936 [MainThread:13012] [django.db.backends:89] [utils:execute] [DEBUG]- (0.007) SELECT `blog_user`.`id`, `blog_user`.`password`, `blog_user`.`last_login`, `blog_user`.`is_superuser`, `blog_user`.`username`, `blog_user`.`first_name`, `blog_user`.`last_name`, `blog_user`.`email`, `blog_user`.`is_staff`, `blog_user`.`is_active`, `blog_user`.`date_joined`, `blog_user`.`avatar`, `blog_user`.`qq`, `blog_user`.`mobile`, `blog_user`.`url` FROM `blog_user` WHERE `blog_user`.`username` = 'admin'; args=('admin',)
Email address: [email protected]
Password:
Password (again):
2017-01-02 12:43:12,418 [MainThread:13012] [django.db.backends:89] [utils:execute] [DEBUG]- (0.001) INSERT INTO `blog_user` (`password`, `last_login`, `is_superuser`, `username`, `first_name`, `last_name`, `email`, `is_staff`, `is_active`, `date_joined`, `avatar`, `qq`, `mobile`, `url`) VALUES ('pbkdf2_sha256$20000$9KrDNK7KQYjA$qd6ZyIrsYlbP5DWyu06kfCJuCD/kWXSamf7kH5bc0pA=', NULL, 1, 'admin', '', '', '[email protected]', 1, 1, '2017-01-02 04:43:12.388000', 'avatar/default.png', NULL, NULL, NULL); args=[u'pbkdf2_sha256$20000$9KrDNK7KQYjA$qd6ZyIrsYlbP5DWyu06kfCJuCD/kWXSamf7kH5bc0pA=', None, True, 'admin', u'', u'', u'[email protected]', True, True, u'2017-01-02 04:43:12.388000', u'avatar/default.png', None, None, None]
Superuser created successfully.
启动服务并登陆后台查看,此时只能管理Groups的对象
以默认的方式将所有的Modules注册到admin中【admin.py】
from django.contrib import admin
from models import *
# Register your models here.
admin.site.register(User)
admin.site.register(Tag)
admin.site.register(Article)
admin.site.register(Category)
admin.site.register(Comment)
admin.site.register(Links)
admin.site.register(Ad)
刷新页面,自定义的其他模块都能通过后台管理
4 自定义ModelAdmin(以文章的Models为例)
Model中关于Admin的一些配置:
fields\exclude
fieldsets
list_display
list_display_links
list_editable
list_filter
inlines
自定义一个ArticleAdmin
class ArticleAdmin(admin.ModelAdmin):
# admin 选项控制变更列表所显示的列
list_display = ('title', 'desc', 'click_count',)
# admin 选项控制变更列表可以链接的列
list_display_links = ('title', 'desc',)
# admin 选项控制变更列表可以直接编辑的列
list_editable = ('click_count',)
fieldsets = (
(None, {
'fields': ('title', 'desc', 'content')
}),
('高级设置', {
'classes': ('collapse',),
'fields': ('click_count', 'is_recommend', 'user', 'category', 'tag')
}),
)
# 默认Django的ModelAdmin来注册
# admin.site.register(Article)
# 使用自定义的ModelAdmin来注册
admin.site.register(Article, ArticleAdmin)
4.1 默认的管理界面:使用默认的方式注册
4.2 自定义的管理界面:ArticleAdmin
可以根据需求定义文章列表显示和可编辑内容
5 富文本编辑器
5.1 下载kindeditor
kindeditor下载链接
将kindeditor加入到项目中,删除不需要的文件
5.2 定义ModelAdmin的媒体文件
【admin.py】
class ArticleAdmin(admin.ModelAdmin):
class Media:
js = (
'/static/js/kindeditor-4.1.10/kindeditor-min.js',
'/static/js/kindeditor-4.1.10/lang/zh_CN.js',
'/static/js/kindeditor-4.1.10/config.js',
)
5.3 修改kindeditor的配置文件
【config.js】
KindEditor.ready(function (K) {
window.editor = K.create('textarea[name="content"]', {
width: '800',
height: '200',
});
});
6 图片文件上存功能
6.1 【ImageField】对应图片上存功能配置
【settings.py】
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
【urls.py】
from django.conf import settings
urlpatterns = [
url(r"^uploads/(?P.*)$", "django.views.static.serve", {"document_root": settings.MEDIA_ROOT,}),
]
6.2 kindeditor图片上存的设置
处理图片上存文件的函数【upload.py】
# coding: utf-8
# author: spareribs
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}
路由设置【urls.py】
from django.conf.urls import 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"]', {
width: '800',
height: '200',
//图片上存路径
uploadJson: '/admin/upload/kindeditor',
});
});
测试富文本编辑器中的文件上存
欢迎留言,博文会持续更新~~