############### xadmin安装和配置 ###############
""" 环境: Python3.6.3 django1.11.11 创建django项目 首先你想要把项目创建到哪一个目录,然后进入目录,执行命令: django-admin startproject test1 #(项目名) 源码安装方式 1, 从https://github.com/sshwsfc/xadmin 下载xadmin zip文件,然后解压。 2, 在项目app下,比如user下新建文件夹extra_app,将解压后的文件夹xadmin拷贝到extra_app中, 3, 然后在文件夹extra_app上点击右键选择'Mark Directory as Sources Root'。 创建完extra_apps,需要在settings中配置一下extra_apps。设置为可搜索的路径。 import os import sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,os.path.join(BASE_DIR,'apps')) sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps')) # 把extra_apps文件夹添加到搜索目录中 然后在项目的settings.py中添加如下配置 INSTALLED_APPS = [ ..... 'xadmin', 'crispy_forms', 'reversion', ] 假如你是用的MySql数据库,进行如下配置 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'USER': 'root', 'PASSWORD': '123456', 'HOST': '139.107.172.158', 'PORT': '3306', } } 同时可以把语言改成中文,时区改成上海 LANGUAGE_CODE = 'zh-Hans' TIME_ZONE = 'Asia/Shanghai' USE_TZ = False # 如果没有国际化的需求写False,否则数据中插入时间时,有警告。 下一步配置路由,打开项目的urls.py做如下修改 import xadmin urlpatterns = [ ... url(r'^xadmin/', xadmin.site.urls), ] 数据库迁移: 生成迁移 python manage.py makemigrations 执行迁移 python manage.py migrate 到这一步其实就可以跑起来了 python mange.py runserver 然后访问http://127.0.0.1:8000/xadmin/,应该就是登录界面了 """
############### model管理 ###############
# adminx.py class CashTitleContentAdmin(object): # 菜单的图标 model_icon = 'fa fa-image' # 列表显示内容 list_display = ('subtitle', 'content_cash', ) # list_display_links 设置默认可编辑字段 list_display_links = ('subtitle', ) # # 分页显示 # list_per_page = settings.list_per_page # 过滤器 list_filter = ('content_cash',) # 表单显示内容 fields = ('subtitle', 'content_cash', ) # 搜索字段 search_fields = ('subtitle', 'content_cash__title', ) xadmin.site.register(cash_title_content, CashTitleContentAdmin)
############### app名称的修改 ###############
# app名为users下的apps.py from django.apps import AppConfig class UsersConfig(AppConfig): # 设置app图标 app_icon = 'fa fa-line-chart' # app名 name = 'users' verbose_name = u'用户管理' # __init__.py default_app_config='users.apps.UsersConfig'
############### 全局配置和基础配置 ###############
class BaseSetting(object): """xadmin的基本配置""" enable_themes = True # 开启主题切换功能 use_bootswatch = True # 支持切换主题 xadmin.site.register(views.BaseAdminView, BaseSetting) class GlobalSettings(object): site_title = "协同办公平台后台管理系统" site_footer = "Copyright © 2019-2021 xxx科技. Version1.0.0" menu_style = "accordion" # 导航菜单折叠 xadmin.site.register(views.CommAdminView, GlobalSettings)
主题修改无效的解决方案:
这边使用requests库来替代httplib2.在xadmin的源码目录下修改xadminplugins hemes.py
:

#coding:utf-8 from __future__ import print_function import httplib2 from django.template import loader from django.core.cache import cache from django.utils import six from django.utils.translation import ugettext as _ from xadmin.sites import site from xadmin.models import UserSettings from xadmin.views import BaseAdminPlugin, BaseAdminView from xadmin.util import static, json import six if six.PY2: import urllib else: import urllib.parse import requests THEME_CACHE_KEY = 'xadmin_themes' class ThemePlugin(BaseAdminPlugin): enable_themes = False # {'name': 'Blank Theme', 'description': '...', 'css': 'http://...', 'thumbnail': '...'} user_themes = None use_bootswatch = False default_theme = static('xadmin/css/themes/bootstrap-xadmin.css') bootstrap2_theme = static('xadmin/css/themes/bootstrap-theme.css') def init_request(self, *args, **kwargs): return self.enable_themes def _get_theme(self): if self.user: try: return UserSettings.objects.get(user=self.user, key="site-theme").value except Exception: pass if '_theme' in self.request.COOKIES: if six.PY2: func = urllib.unquote else: func = urllib.parse.unquote return func(self.request.COOKIES['_theme']) return self.default_theme def get_context(self, context): context['site_theme'] = self._get_theme() return context # Media def get_media(self, media): return media + self.vendor('jquery-ui-effect.js', 'xadmin.plugin.themes.js') # Block Views def block_top_navmenu(self, context, nodes): themes = [ {'name': _(u"Default"), 'description': _(u"Default bootstrap theme"), 'css': self.default_theme}, {'name': _(u"Bootstrap2"), 'description': _(u"Bootstrap 2.x theme"), 'css': self.bootstrap2_theme}, ] select_css = context.get('site_theme', self.default_theme) if self.user_themes: themes.extend(self.user_themes) if self.use_bootswatch: ex_themes = cache.get(THEME_CACHE_KEY) if ex_themes: themes.extend(json.loads(ex_themes)) else: ex_themes = [] try: # h = httplib2.Http() # resp, content = h.request("https://bootswatch.com/api/3.json", 'GET', '', # headers={"Accept": "application/json", "User-Agent": self.request.META['HTTP_USER_AGENT']}) # if six.PY3: # content = content.decode() # watch_themes = json.loads(content)['themes'] # ex_themes.extend([ # {'name': t['name'], 'description': t['description'], # 'css': t['cssMin'], 'thumbnail': t['thumbnail']} # for t in watch_themes]) flag = False # 假如为True使用原来的代码,假如为Flase,使用requests库来访问 if flag: h = httplib2.Http() resp, content = h.request("http://bootswatch.com/api/3.json", 'GET', '', headers={"Accept": "application/json", "User-Agent": self.request.META['HTTP_USER_AGENT']}) if six.PY3: content = content.decode() watch_themes = json.loads(content)['themes'] else: content = requests.get("https://bootswatch.com/api/3.json") if six.PY3: content = content.text.decode() watch_themes = json.loads(content.text)['themes'] ex_themes.extend([ {'name': t['name'], 'description': t['description'], 'css': t['cssMin'], 'thumbnail': t['thumbnail']} for t in watch_themes]) except Exception as e: print(e) cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600) themes.extend(ex_themes) nodes.append(loader.render_to_string('xadmin/blocks/comm.top.theme.html', {'themes': themes, 'select_css': select_css})) site.register_plugin(ThemePlugin, BaseAdminView)
############### xadmin里Model分类管理(proxy=True) ###############
# adminx.py import xadmin from .models import Teacher, TeacherMan class TeacherAdmin(object): # 显示的字段 list_display = ["teacher_name", "sex", "tel", "mail"] # 注册新的表 class TeacherManAdmin(TeacherAdmin): # 显示的字段 list_display = ["teacher_name", "sex", "tel", "mail"] def queryset(self): qs = super(TeacherAdmin, self).queryset() qs = qs.filter(sex="M") # 筛选 sex="男" return qs xadmin.site.register(Teacher, TeacherAdmin) xadmin.site.register(TeacherMan, TeacherManAdmin)
############### 根据登录用户或组过滤数据--queryset ###############
class DeviceAdmin(object): ... def queryset(self): """函数作用:使当前登录的用户只能看到自己负责的设备""" qs = super(DeviceAdmin, self).queryset() if self.request.user.is_superuser: return qs return qs.filter(area_company=Group.objects.get(user=self.request.user))
############### xadmin安装和配置 ###############
############### xadmin安装和配置 ###############
############### xadmin安装和配置 ###############