django【第四篇】后台管理

admin

注册model

创建项目会自动生成后台管理系统

createsuperuser  //输入账号密码:admin,admin123

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_TZ = False
汉化
from django.contrib import admin

# Register your models here.

from models import UserProfile


class UserProfileAdmin(admin.ModelAdmin):
    pass

admin.site.register(UserProfile,UserProfileAdmin)
注册user model到后台管理系统

点击用户信息

再注册一个用户,若能成功添加,后台管理系统没有问题

xadmin

把users app下的admin.py内容注释

workon myenv
pip install xadmin
setting.py加入app 'xadmin','crispy_forms',url.py中的admin修改为xadmin

from django.conf.urls import url
# from django.contrib import admin
import xadmin

urlpatterns = [
    url(r'^xadmin/', xadmin.site.urls),
]
url.py

migrations
migrate

xadmin会自动发现各个app下的adminx文件,并根据该文件注册model

 源码安装xadmin(推荐)

xadmin源码托管在github

源码依赖django-crispy-forms

pip uninstall xadmin
https://github.com/sshwsfc/xadmin,把其中的xadmin目录添加到项目下的extra_apps包下
setting添加  sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))

makemigrations
migrate

注册model

 xadmin全局配置

配置app在后台显示的中文名称

默认显示为app文件名(英文)(如果是pip安装的xadmin,可能有BUG,不会生效)

配置users app

# _*_ encoding:utf-8 _*_
from __future__ import unicode_literals

from django.apps import AppConfig


class UsersConfig(AppConfig):
    name = 'users'
    verbose_name = u"用户操作"
apps.py
default_app_config = "users.apps.UsersConfig"
__init__.py

 其它同上,省略

 配置主题

from xadmin import views

class BaseSetting(object):
    enable_themes = True
    use_bootswatch = True


xadmin.site.register(views.BaseAdminView, BaseSetting)
users/adminx.py

 

admin富文本编辑器

参考

http://blog.csdn.net/gamer_gyt/article/details/66598750

常见的富文本编辑器

ckeditor、ueditor、kindeditor、tinymce、...

添加富文本编辑器的几种方式

1、使用第三方的一些库,如django-ckeditor
(https://pypi.python.org/pypi/django-ckeditor)
2、在admin中定义富文本编辑器的widget
3、通过定义ModelAdmin的媒体文件

步骤:
1、下载kindeditor
2、定义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',
)
3、修改kindeditor的配置文件

config.js

KindEditor.ready(function(K) {
                K.create('textarea[name=content]',{
                    width:'800px',
                    height:'300px',
                    uploadJson: '/admin/upload/kindeditor',
                });
        });

文件上传  

1、如何配置上传的文件路径
2、如何解决富文本编辑器文件上传的问题

配置上传:
1、在settings.py中配置MEDIA_URL和MEDIA_ROOT
2、urls.py中配置路由

url(r"^uploads/(?P<path>.*)$", \
"django.views.static.serve", \
{"document_root": settings.MEDIA_ROOT,}),

3、在model中设置图片的上传位置和路径

config.js:

KindEditor.ready(function(K) {
K.create('textarea[name="content"]', {
width : "800px",
height : "200px",
uploadJson: '/admin/upload/kindeditor',
});
});

urls配置:

url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),

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}
View Code

 

  

 

posted @ 2017-05-08 14:41  沐风先生  阅读(410)  评论(0编辑  收藏  举报