django(14)Xadmin后台介绍
Posted fqh202
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django(14)Xadmin后台介绍相关的知识,希望对你有一定的参考价值。
使用步骤
- 1、安装xadmin模块,推荐源码安装;
- 2、在
setting.py
将xadmin
和crispy_forms
放进INSTALLED_APPS
中; - 3、同步xadmin自带的表:
python manage.py migrate
4、修改
url.py
:import xadmin urlpatterns = [ url(r'^xadmin/', xadmin.site.urls), ]
源码安装Xadmin
- 1、由于xadmin源码是最新版本的,还可以自定义功能,所以推荐源码安装,github下载源码:https://github.com/sshwsfc/xadmin
- 注意选择和django对应的版本,有1.7、1.8、2.0三个版本
- 要使用xadmin插件最好就在项目初期就安装xamdin
2、解压并取出xadmin文件夹,放在项目根目录;
3、新建
extra_apps
文件夹, 将xadmin文件夹(注意是内部的xadmin文件夹)放进去;4、同样配置文件设置:
sys.path.insert(1, os.path.join(BASE_DIR, ‘extra_apps‘))
;5、先安装相关依赖包,避免出错:
# requirement.txt django-crispy-forms>=1.6.0 django-import-export>=0.5.1 django-reversion>=2.0.0 django-formtools==2.0 future==0.15.2 httplib2==0.9.2 six==1.10.0
Xadmin中App的Model注册
- 1、每个app下新建
adminx.py
(注意文件名不能写错)文件,xadmin会默认查询此文件; 2、代码如下:
import xadmin from .models import Author,Publisher,Book class BookAdmin(object): # 选择显示的字段 list_display = ['id','title','price','publisher'] # 添加字段搜索,不能添加外键字段,否则会报错 search_fields = ['title','price'] # 界面自带导出功能, 可以导出多种格式 # 过滤器 list_filter = ['publisher', 'price'] # 按照students_num降序排列,同时也可以在标题栏点击降序 ordering = ['-price'] # 自定制图标显示 model_icon = 'fa fa-beer' # css文件:xadmin/static/xadmin/vendor/font-awesome/css/font-awesome.css # 可以下载最新版本的,http://fontawesome.dashgame.com/,直接复制标签的类即可使用 # 设置只读字段,在修改页面为p标签 readonly_fields = ['price', ] # 设置不显示某些字段,修改页面隐藏该字段 exclude = ['price'] # 只要是涉及到此model的外键都会显示查询,不会出现下拉框,优点是当数据量过大时候,不会加载所有数据 relfield_style = 'fk-ajax' # 设置在列表页页面可编辑的字段 list_editable = ['title', 'price','publisher'] xadmin.site.register(Book, BookAdmin) xadmin.site.register(Author) xadmin.site.register(Publisher)
- 3、注意:user表会自动生成,无须注册!;
4、若有多个app的话,添加字段需要仔细点!
全局设置
1、主题修改:
from xadmin import views
class BaseSetting(object):
# 增加主题插件
enable_themes = True
use_bootswatch = True
xadmin.site.register(views.base.BaseAdminView, BaseSetting)
# 报错!
File "C:UsersAdministratorPycharmProjectsxadmin_tstxadminsites.py", line 122, in register
raise AlreadyRegistered('The admin_view_class %s is already registered' % model.__name__)
xadmin.sites.AlreadyRegistered: The admin_view_class BaseAdminView is already registered
2、全局页头和页脚配置:
# app01/xadmin.py
from xadmin import views
class GlobalSetting(object):
site_title = '学习在线后台管理系统'
site_footer = '学习在线'
# 折叠左侧app菜单
menu_style = "accordion"
xadmin.site.register(xadmin.views.base.CommAdminView, GlobalSetting)
3、修改左侧菜单App显示名称:
# app/apps.py
class CourseConfig(AppConfig):
name = 'appname'
verbose_name = '要显示的名称'
# app/__init__.py
default_app_config = "appname.apps.CourseConfig"
4、类函数字段显示:
# models.py
class Course():
def get_chap_num(self):
return self.chapter_set.all().count()
# 中文显示,若没有定义则只会显示get_chap_num
get_chap_num.short_description='章节数'
def my_link(self):
from django.utils.safestring import mark_safe
return mark_safe('<a href="https://www.baidu.com">链接</a>')
my_link.short_description='章节数'
# adminx.py
class CourseAdmin():
list_display=['get_chap_num','my_link']
最终结果展示:
集成django-ueditor插件
- 1、源码下载:https://github.com/twz915/DjangoUeditor3
- 注意此版本兼容python3,优先采用此版本。
2、在虚拟环境下安装zip文件:
pip install DjangoUeditor-master.zip
,或者将源码包放在extra_apps文件夹下;3、settings中配置:
INSTALLED_APPS = [ 'DjangoUeditor', ... ] # 必须要存在,方便加载ueditor的js和css等样式 STATIC_URL = '/static/' STATICFILES_DIRS=[os.path.join(BASE_DIR, 'static')] # 必须存在,上传图片或文件需要 MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
4、将
/env/DjangoUeditor/static/ueditor
文件移动至项目目录下的static中,否则编辑页面不会加载插件样式;5、将
/env/DjangoUeditor/templates/ueditor.html
的模板移动至项目目录下templates文件夹中,以便加载模板;6、配置路由:
from django.views.static import serve from xadmin_tst import settings # 仅限于debug模式 urlpatterns += [ url(r'^ueditor/',include('DjangoUeditor.urls' )) # 文件上传 url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), ]
7、修改model中需要使用ueditor的字段:
class Course(models.Model): # 配置ueditor detail = UEditorField(verbose_name='课程详情', width=600, height=300, imagePath="courses/ueditor/", filePath="courses/ueditor/",default='')
8、在
xadminplugins
文件下新建ueditor.py
文件:import xadmin from xadmin.views import BaseAdminPlugin, CreateAdminView, ModelFormAdminView, UpdateAdminView from DjangoUeditor.models import UEditorField from DjangoUeditor.widgets import UEditorWidget from django.conf import settings class XadminUEditorWidget(UEditorWidget): def __init__(self, **kwargs): self.ueditor_options = kwargs self.Media.js = None super(XadminUEditorWidget,self).__init__(kwargs) class UeditorPlugin(BaseAdminPlugin): def get_field_style(self, attrs, db_field, style, **kwargs): if style == 'ueditor': if isinstance(db_field, UEditorField): widget = db_field.formfield().widget param = {} param.update(widget.ueditor_settings) param.update(widget.attrs) return {'widget':XadminUEditorWidget(**param)} return attrs def block_extrahead(self, context, nodes): js = '<script type="text/javascript" src="%s"></script>' %(settings.STATIC_URL + "ueditor/ueditor.config.js") js += '<script type="text/javascript" src="%s"></script>' %(settings.STATIC_URL + "ueditor/ueditor.all.min.js") nodes.append(js) xadmin.site.register_plugin(UeditorPlugin, UpdateAdminView) xadmin.site.register_plugin(UeditorPlugin, CreateAdminView)
9、在
xadminplugins\__init__.py
文件中配置:PLUGINS = ( 'ueditor', )
10、
course/adminx.py
中配置:class CourseAdmin(object): # detail就是要显示为富文本的字段名 style_fields = {"detail": "ueditor"}
编辑页面显示:
8、前端页面渲染配置:
# views.py from django.shortcuts import render from app01.models import Book def get_desc(request,id): b = Book.objects.filter(id=id).first() if b: return render(request,'book.html',locals()) # index.html {% autoescape off %} {{ b.detail }} {% endautoescape %}
页面显示
以上是关于django(14)Xadmin后台介绍的主要内容,如果未能解决你的问题,请参考以下文章