Django项目搭建
1、新建项目文件夹pro,新建文件夹venv,创建虚拟环境并激活
bash
python -m venv django-test
cd django-test
cd Scripts
activate
2、导入django,终端输入命令
bash
pip install Django==3.2.7 -i https://pypi.mirrors.ustc.edu.cn/simple/
pip install PyMySQL==0.9.2 -i https://pypi.mirrors.ustc.edu.cn/simple/
pip install xadmin-django==3.0.2 -i https://pypi.mirrors.ustc.edu.cn/simple/
pip install mysqlclient==2.0.1 -i https://pypi.mirrors.ustc.edu.cn/simple/
3、进入项目文件夹
bash
cd ..
cd ..
cd ..
cd pro
4、创建django项目
bash
django-admin startproject django-test
5、切换到项目根目录,创建子应用
bash
cd django-test
django-admin startapp test
6、创建数据库
bash
create database django-test;
7、修改settings.py配置文件
允许所有访问
python
ALLOWED_HOSTS = ['*']
添加子应用
python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'xadmin',
'crispy_forms',
'crispy_bootstrap3',
'test'
]
使用mysql数据库,注释DATABASES,修改:
python
ip = '127.0.0.1'
DATABASE_NAME = 'django-test' # mysql数据库名称
DATABASE_USER = 'root' # mysql数据库用户名
DATABASE_PASS = '123456' # mysql数据库密码
DATABASE_HOST = ip # mysql数据库IP
DATABASE_PORT = 3306 # mysql数据库端口
# 配置数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 修改数据库为MySQL,并进行配置
'NAME': DATABASE_NAME, #
'USER': DATABASE_USER, # 用户名
'PASSWORD': DATABASE_PASS, # 密码
'HOST': DATABASE_HOST,
'PORT': DATABASE_PORT,
'OPTIONS': {'charset': 'utf8mb4', }
}
}
使用中文
python
LANGUAGE_CODE = 'zh-hans' # 使用中国时区
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
在django-test下新建文件夹static,配置静态文件路由
python
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# STATIC_ROOT = os.path.join(BASE_DIR, 'static') # 收集静态文件时打开,然后关闭STATICFILES_DIRS
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
8、models.py数据表
创建一系列数据表,例:
python
from django.db import models
class MetaData(models.Model):
name = models.CharField(max_length=100, null=True, blank=True, verbose_name='名称')
describe = models.CharField(max_length=20, null=True, blank=True, verbose_name='描述')
time = models.DateTimeField(verbose_name='时间')
class Meta:
db_table = 'subway_metadata'
verbose_name_plural = "元数据"
verbose_name = verbose_name_plural
def __str__(self):
return self.name
9、urls.py路由配置
修改django-test/urls.py
python
import xadmin
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.static import serve
from subway_warehouse import settings
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path("", include("test.urls")),
re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
# re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATICFILES_DIRS}), # 收集静态文件时关闭
path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}), # 收集静态文件时打开,然后关闭STATICFILES_DIRS
]
python
from django.urls import path
urlpatterns = [
]
10、数据迁移,终端输入命令
bash
python manage.py makemigrations
python manage.py migrate
11、创建缓存表
bash
python manage.py createcachetable
12、收集静态文件,django-test/settings.py文件改为
python
STATIC_URL = '/static/'
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, 'static'),
# ]
STATIC_ROOT = os.path.join(BASE_DIR, 'static') # 收集静态文件时打开,然后关闭STATICFILES_DIRS
然后执行
bash
python manage.py collectstatic
执行成功后,django-test/settings.py再改为
python
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# STATIC_ROOT = os.path.join(BASE_DIR, 'static') # 收集静态文件时打开,然后关闭STATICFILES_DIRS
修改django-test/urls.py
python
import xadmin
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.static import serve
from subway_warehouse import settings
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path("", include("test.urls")),
re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATICFILES_DIRS}), # 收集静态文件时关闭
# path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}), # 收集静态文件时打开,然后关闭STATICFILES_DIRS
]
13、创建后台管理员
bash
python manage.py createsuperuser
设置邮箱、账号、密码
bash
设置账号为 root
邮箱为 1@qq.com
密码为 test-root
14、后台管理
子应用test下创建adminx.py文件,内容例:
python
import xadmin
from django.http import HttpResponseRedirect
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from xadmin import views
from django.conf import settings
from .models import *
# https://fontawesome.dashgame.com/ 图标字体网站
# 基础设置
class BaseSetting(object):
enable_themes = True # 使用主题
use_bootswatch = True
# 全局设置
class GlobalSettings(object):
site_title = '数据管理系统' # 标题
site_footer = mark_safe(settings.SITE_FOOTER) # 页尾
site_url = '/'
menu_style = 'accordion' # 设置左侧菜单 折叠样式
# 地铁元数据管理
class MetaDataAdmin(object):
search_fields = ['name', 'device_code'] # 检索字段
list_display = ['id', 'name', 'describe', 'time'] # 要显示的字段
list_per_page = 30 # 默认每页显示多少条记录,默认是100条
model_icon = 'fa fa-users' # 左侧小图标
list_editable = ['name'] # 可编辑字段
# 控制是否显示书签功能,False表示关闭
show_bookmarks = False
xadmin.site.register(views.CommAdminView, GlobalSettings)
xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(MetaData, MetaDataAdmin)
修改test/apps.py
python
from django.apps import AppConfig
class SubwayConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'test'
verbose_name = "django测试系统"
修改test/__init__.py
python
default_app_config = 'book.apps.BookConfig'
运行,终端输入命令
bash
python manage.py runserver
点击http://127.0.0.1:8000/进入浏览器访问,需要加上/xadmin访问
也可以直接在浏览器输入http://127.0.0.1:8000/xadmin/访问
账号:root
密码:test_root
登录成功