xadmin:Python的第三方库,用作Django的插件,提供了更美观的admin页面。
使用时基本不必修改Django项目的原本代码,主要是针对admin.py做出改动,比如定义Action的方法要改,显示message的方法也要改。
用法
-
安装:pip install xadmin2
-
在settings.py的INSTALLED_APPS[]中加入’xadmin’和’crispy_forms’。如下:
```pythonINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',"django_mysql",'xadmin','crispy_forms',]```
-
更新数据库:
python manage.py makemigrations
python manage.py migrate
-
在主urls.py中加入URL:
import xadminurlpatterns = [path('xadmin/', xadmin.site.urls),
]
-
在每个app下创建adminx.py,格式如下:
import xadmin
from xadmin import views
from xadmin.plugins.actions import BaseActionViewfrom .models import Project@xadmin.sites.register(views.BaseAdminView)
class BaseSetting(): enable_themes = True use_bootswatch = True @xadmin.sites.register(views.CommAdminView)
class GlobalSetting(): site_title = "管理平台" site_footer = "管理平台" menu_style = "accordion" class MyAction(BaseActionView): action_name = "my_action" description = "参数化构建" model_perm = "change" def do_action(self, queryset): try:for i in queryset:...self.message_user(message="Done", level="success") except Exception as e:self.message_user(e, "error")@xadmin.sites.register(Project)
class ProjectAdmin():list_display = ["project_name"]search_fields = ["project_name"]fieldsets = [(None, {"fields": ["project_name"]})]actions = [MyAction]
-
运行测试服务器python manage.py runserver 0.0.0.0:80
,访问http://127.0.0.1:xadmin/
即可。