前置条件

win10电脑
已安装python3
并且安装PyCharm
已安装mysql数据库

开始安装Django

pip install Django

初次安装错


百度找解决方法
原因是下载超时

两种解决方式:
切换源为国内的(推荐)

在window 10 的用户文件下面创建pip文件夹并文件夹中创建pip.ini文件

[global]
index-url = http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host = mirrors.aliyun.com
设置超时时间
pip3 --default-timeout=100 install -U Django

安装mysqlclient

 pip install mysqlclient

安装会报错

Installing collected packages: mysqlclient
    Running setup.py install for mysqlclient ... error
    ERROR: Command errored out with exit status 1:
     command: 'd:\program files\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\jiqfu\\AppData\\Local\\Temp\\pip-install-wlllnppk\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\jiqfu\\AppData\\Local\\Temp\\pip-install-wlllnppk\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\jiqfu\AppData\Local\Temp\pip-record-4ny11c1q\install-record.txt' --single-version-externally-managed --compile
         cwd: C:\Users\jiqfu\AppData\Local\Temp\pip-install-wlllnppk\mysqlclient\
    Complete output (24 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib.win32-3.8
    creating build\lib.win32-3.8\MySQLdb
    copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb
    copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb
    copying MySQLdb\compat.py -> build\lib.win32-3.8\MySQLdb
    copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb
    copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb
    copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb
    copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb
    copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb
    creating build\lib.win32-3.8\MySQLdb\constants
    copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants
    copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants
    copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants
    copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants
    copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants
    copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants
    running build_ext
    building 'MySQLdb._mysql' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'd:\program files\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\jiqfu\\AppData\\Local\\Temp\\pip-install-wlllnppk\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\jiqfu\\AppData\\Local\\Temp\\pip-install-wlllnppk\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\jiqfu\AppData\Local\Temp\pip-record-4ny11c1q\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output.


解决方式搜集到两种
第一种是安装环境

第二种是下载mysqlclient‑1.4.6‑cp38‑cp38‑win32.whl 安装

下载地址
https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python

64位的安装失败,之后下载了32位的安装成功
安装命令

pip install mysqlclient-1.4.6-cp38-cp38-win32.whl

创建项目

django-admin startproject blog

启动项目

python manage.py runserver 0.0.0.0:8000

配置连接数据库

注意先创建数据库
blog/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 或者使用mysql.connector.django
        'NAME': 'blog',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

创建应用

django-admin startapp blogBack

创建命令

# 创建Django的表格
python manage.py migrate
# 添加模块
python manage.py makemigrations blogBack
# 创建自定义模块的表
python manage.py migrate blogBack

创建应用和创建项目可以直接使用Pycharm直接创建

安装vue

cnpm install -g @vue/cli

创建vue项目

使用 vui ui进行创建

vue ui
注意:若出现报错
??  Starting GUI...
 ERROR  Error: Cannot find module '@vue/cli/lib/util/rcPath'
Require stack:
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\util\rcFolder.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\util\db.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\context.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\connectors\plugins.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\connectors\configurations.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\schema\configuration.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\type-defs.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\[email protected]@vue-cli-plugin-apollo\graphql-server\index.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\server.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\lib\ui.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\bin\vue.js
D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\util\rcFolder.js:1
Error: Cannot find module '@vue/cli/lib/util/rcPath'
Require stack:
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\util\rcFolder.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\util\db.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\context.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\connectors\plugins.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\connectors\configurations.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\schema\configuration.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\type-defs.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\[email protected]@vue-cli-plugin-apollo\graphql-server\index.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\server.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\lib\ui.js
- D:\java\nodejs\node_modules\node_modules\@vue\cli\bin\vue.js
    at Object.<anonymous> (D:\java\nodejs\node_modules\node_modules\@vue\cli\node_modules\_@[email protected]@@vue\cli-ui\apollo-server\util\rcFolder.js:4:23)
    at Generator.next (<anonymous>)

解决办法 将
node_modules@vue\cli\lib 文件夹复制到

[email protected]node_modules_@@@vue\cli-ui\node_modules@vue\cli

命令执行成功后访问http://localhost:8000/

构建项目

在vue项目下创建文件
vue.config.js

module.exports = {
    assetsDir: 'static'
// 指定`build`时, 在静态文件上一层添加static目录
};

配置Django 整合vue

安装django-cors-headers

pip install django-cors-headers

blog/urls.py 文件添加

from django.contrib import admin
from django.urls import path, re_path
from django.views.generic.base import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^$', TemplateView.as_view(template_name='index.html')),
]

blog/settings.py 文件添加


# 配置静态文件路径
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'blogfront/dist/static'),
]
CORS_ORIGIN_ALLOW_ALL = True

# 第二处修改
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'DIRS': [os.path.join(BASE_DIR, 'templates')],
        # 指定为vue的页面路径
        'DIRS': [os.path.join(BASE_DIR, 'blogfront/dist')],
        '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',
            ],
        },
    },
]
# 第三处修改
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # 自动响应变化
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

完成之后启动项目

创建管理员账号

python manage.py createsuperuser

创建后可访问 http://localhost:8080/admin 登陆

配置细节修改

# 语言修改
LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

# 配置日志输出
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'DEBUG',
        },
    }
}

创建表格

安装支持图片的插件

pip install Pillow

删表重建

1、删除数据库中的表
2、删除图中migrations文件夹中除__init__.py之外的文件

执行以下命令

python manage.py makemigrations
python manage.py migrate

详细教程可查看 https://www.jianshu.com/p/7aa23f044cef

编辑器添加

使用tui.editor
https://github.com/nhn/tui.editor
https://github.com/nhn/toast-ui.vue-editor
具体使用教程参加官网
使用 mavon-editor
https://github.com/hinesboy/mavonEditor
插件添加
https://www.npmjs.com/search?q=markdown-it-plugin&ranking=popularity&page=1&perPage=20
markdown-it-plugin
找到需要的插件进行安装并使用

import Vue from 'vue'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
// import emoji from 'markdown-it-emoji'

Vue.use(mavonEditor)

// const markdownIt = mavonEditor.markdownIt
// markdownIt.use(emoji)
// markdownIt.use(require('markdown-it-deflist'))

关于查询踩了很多坑

最主要的是要根据官方文档来使用,切忌多个文档搜集教程,会出问题的。
相关地址:
lookup_expr相关
https://docs.djangoproject.com/en/3.0/ref/models/querysets/
过滤器教程
https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html

from rest_framework.pagination import PageNumberPagination
from blogBack.serializers import *
from rest_framework import viewsets
from django_filters import rest_framework as filters


# Create your views here.
class StandardResultsSetPagination(PageNumberPagination):
    """
    配置分页规则
    """
    # 设置默认大小
    page_size = 10
    # 设置页大小字段名
    page_size_query_param = 'page_size'
    # 设置页数字段名
    page_query_param = 'page'
    max_page_size = 100


class ArticleFilter(filters.FilterSet):
    title = filters.CharFilter('title', lookup_expr='icontains')

    class Meta:
        model = Article
        fields = ['title', 'category']


class ArticleViewSet(
    viewsets.ModelViewSet
):
    queryset = Article.objects.all()
    # 序列化
    serializer_class = ArticleSerializers
    # 设置过滤器
    filter_backends = (filters.DjangoFilterBackend,)
    # 设置查询条件
    filterset_class = ArticleFilter
    # 设置分页器
    pagination_class = StandardResultsSetPagination


class TagFilter(filters.FilterSet):
    name = filters.CharFilter('name', lookup_expr='icontains')

    class Meta:
        model = Tag
        fields = ['name', ]


class TagViewSet(
    viewsets.ModelViewSet
):
    queryset = Tag.objects.all()
    serializer_class = TagSerializers
    # 设置过滤器
    filter_backends = (filters.DjangoFilterBackend,)
    # 设置查询条件
    filterset_class = TagFilter
    pagination_class = StandardResultsSetPagination

vue history模式路由无法跳转解决

注意 若更改过前端项目的路径,需要调整下面路径

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'DIRS': [os.path.join(BASE_DIR, 'templates')],
        # 指定为vue的页面路径 修改处
        'DIRS': [os.path.join(BASE_DIR, '../blogfront/dist')],
        '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',
            ],
        },
    },
]

配置vue路由,排除后端路由

 urlpatterns = [
    path('admin/', admin.site.urls),
    path('media/<path:path>', serve, {"document_root": MEDIA_ROOT}),
    path('', TemplateView.as_view(template_name='index.html')),
    # 不以admin media api 开头的URI都跳转到 vue的路由上
    re_path(r'^(?!admin|media|api).*', TemplateView.as_view(template_name='index.html')),
]

将数据库切换为MongoDB