django使用xadmin

1、安裝xadmincss

因爲我用的是Django2.0之後的版本python

因此沒法直接經過pip install xadmin來安裝mysql

即便安裝成功了git

也會報亂七八糟的錯誤github

 

https://github.com/sshwsfc/xadminsql

GitHub主頁數據庫

 

pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2django

安裝xadminsession

 

pip install xlsxwriterapp

安裝寫入xlsx格式的Excel文件的庫

pip install pillow

安裝處理圖片的庫

 

pip list

查看已經安裝的包與版本

django-crispy-forms
django-import-export
django-reversion
django-formtools
pillow
xadmin
xlsxwriter
xlwt

應該包含這些模塊

若是沒有

請手動安裝

 

2、建立django工程

django-admin startproject demo

建立工程

python manage.py startapp product

 建立應用

 

在工程的根目錄下面新建static目錄

做爲靜態文件目錄

在工程的根目錄下面新建media目錄

做爲圖片存儲目錄

 

CREATE DATABASE 'demo' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

建立demo數據庫

 

工程的目錄結構

 

 

3、django代碼

配置文件demo/settings.py:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'db@02^k!pw$6kx*0$+9#%2h@vro-*h^+xs%5&(+q*b181&o$)l'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'product.apps.ProductConfig',

'xadmin',
'crispy_forms',
'reversion',
# 添加django-xadmin
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'demo.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'demo.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'demo',
'HOST': '192.168.1.106',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'Abcdef@123456',
}
}
# MySQL數據庫配置


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'zh-hans'
# 簡體中文界面

TIME_ZONE = 'Asia/Shanghai'
# 亞洲/上海時區

USE_I18N = True

USE_L10N = True

USE_TZ = False
# 不使用國際標準時間


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# 定義靜態文件的目錄

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 定義圖片存放的目錄
 

PyMySQL初始化demo/__init__.py:

import pymysql


pymysql.install_as_MySQLdb()

 

路由轉發demo/urls.py:

import xadmin

from django.conf import settings
from django.conf.urls.static import static

from django.urls import path

urlpatterns = [
# path('admin/', admin.site.urls),
path('admin/', xadmin.site.urls),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# 配置圖片文件url轉發

 

模型product/models.py:

from django.db import models


# Create your models here.


class ProductInfo(models.Model):
# 產品表

product_name = models.CharField(max_length=32, verbose_name="產品名稱")
# 產品名稱
product_picture = models.ImageField(blank=True,
null=True,
upload_to="pictures/%Y%m%d",
max_length=255,
verbose_name="產品圖片")
# 產品圖片,數據庫裏面存儲的是圖片的相對路徑
product_describe = models.CharField(max_length=255, verbose_name="產品描述")
# 產品描述
product_manager = models.CharField(max_length=11, verbose_name="產品經理")
# 產品經理
create_time = models.DateTimeField(auto_now_add=True, verbose_name="建立時間")
# 建立時間
update_time = models.DateTimeField(auto_now=True, blank=True, null=True, verbose_name="修改時間")
# 修改時間

class Meta:
db_table = 'product_info'
# 設置表名,默認表名是:應用名稱_模型類名
# 帶有應用名的表名太長了

verbose_name = '產品管理'
verbose_name_plural = "產品管理"

def __str__(self):
return self.product_name

 

應用管理product/apps.py:

from django.apps import AppConfig


class ProductConfig(AppConfig):
name = 'product'
verbose_name = '產品管理'

 

後臺註冊product/admin.py:

import xadmin

# Register your models here.
from xadmin import views

from product.models import ProductInfo


class ProductInfoAdmin(object):
list_display = [
'id',
'product_name',
'product_picture',
'product_describe',
'product_manager',
'create_time',
'update_time',
]
# 要顯示的字段列表

ordering = ['id']
# 按照id順序排列,若是是倒序-id

search_fields = ['product_name', 'product_manager']
# 要搜索的字段

list_filter = ['product_name', 'create_time', 'update_time']
# 要篩選的字段

show_detail_fields = ['product_name', 'product_picture']
# 要展現詳情的字段

list_editable = ['product_name', 'product_picture',
'product_describe', 'product_manager']
# 列表可直接修改的字段

list_per_page = 10
# 分頁

# model_icon = 'fa fa-laptop'
# 配置模型圖標,也能夠在GlobalSetting裏面配置


class BaseSetting(object):
enable_themes = True
use_bootswatch = True
# 開啓主題自由切換


class GlobalSetting(object):
global_search_models = [ProductInfo]
# 配置全局搜索選項,默認搜索組、用戶、日誌記錄
site_title = "測試平臺"
# 標題
site_footer = "測試部"
# 頁腳

menu_style = "accordion"
# 左側菜單收縮功能
apps_icons = {
"product": "fa fa-music",
}
# 配置應用圖標,即一級菜單圖標
global_models_icon = {
ProductInfo: "fa fa-film",
}
# 配置模型圖標,即二級菜單圖標


xadmin.site.register(ProductInfo, ProductInfoAdmin)
# 註冊模型

xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSetting)

 

 

4、建立django管理員

python manage.py collectstatic

複製xadmin靜態文件

此時可看到static目錄下新增了靜態文件

原來是空的

 

icon圖標的樣式文件是

static/xadmin/vendor/font-awesome/css/font-awesome.css

 

 

python manage.py makemigrations

激活模型

python manage.py migrate

遷移

python manage.py createsuperuser

建立超級管理員帳號

 

 

5、django後臺頁面

python manage.py runserver

啓動服務

http://127.0.0.1:8000/admin/

 

 

 

 

 

6、注意事項:

須要修改Python源碼

python3.6/site-packages/django/forms/boundfield.py

把第93行

renderer=self.form.renderer,

註釋掉

# renderer=self.form.renderer,

不然在點擊右上角=>增長~增長用戶小組件時

會拋出異常

TypeError: render() got an unexpected keyword argument 'renderer'

相關文章
相關標籤/搜索