如何使用Django源码-windows/pycharm
发布日期:2022-02-09 20:39:15 浏览次数:8 分类:技术文章

本文共 14640 字,大约阅读时间需要 48 分钟。

一、win系统

安装数据库并设置环境变量

数据库安装8.0版本的数据库,因为Django不再支持5.5版本的数据库。

否则在做数据库迁移(python manage.py migrate)的时候会报错。

图片.png

1、安装python3+

根据你的Windows版本(64位还是32位)从Python的官方网站下载Python 3.7对应的或(网速慢的同学请移步),然后,运行下载的EXE安装包:

07.png

特别要注意勾上Add Python 3.7 to PATH,然后点“Install Now”即可完成安装。

安装成功后,打开命令提示符窗口,敲入python后,会出现两种情况:

 

看到上面的画面,就说明Python安装成功!

08.png

2、创建虚拟环境(三种方式,有pycharm建议选pycharm)

最为快捷的方式是copy已有的venv文件夹到项目目录下。进入虚拟环境,检查安装的第三方库。

  • 其他三种方式

进入项目根目录文件夹,在地址栏输入cmd,进入终端

图片.png

 

图片.png

方法一:(和pycharm一样的原理,无界面操作)

安装 virtualenv工具,pip install virtualenv

 

创建虚拟环境,virtualenv  -p python3 venv,环境名称为venv

venv\Scripts\activate  # 进入虚拟环境

cd company   # 进入项目根目录

方法二:(命令行推荐,安装第三方库时要进入虚拟环境安装)

使用python3自带模块:

python -m venv venv    # 创建

venv\Scripts\activate  # 进入虚拟环境在该虚拟环境下安装项目所需的第三方库。该第三方库将在debug和run的时候使用。

cd company   # 进入项目根目录

方法三:(pycharm推荐,安装第三方库也要在pycharm中安装)

首先,将文件夹导入工程。

图片.png

按照以下步骤完成虚拟环境配置:

  1. 打开Project Interpreters页面:文件(file)——>设置(setting)——>项目(Project)——>Project Interpreters;
  2. 点击右边的配置按钮,选择Add。这时会弹出Virtual Environment的对话框;

 

参数说明

  • Name中填写新虚拟环境的名字,或者使用默认名字,方便以后安装第三方包和其他项目使用;
  • 在Location中填写新环境的文件目录;
  • 在Base interpreter下拉框中选择Python解释器;
  • 勾选Inherit global site-packages可以使用base interpreter中的第三方库,不选将和外界完全隔离;
  • 勾选Make available to all projects可将此虚拟环境提供给其他项目使用。

 

新建Django项目时,配置虚拟环境

File--->New Project--> 出现如下图,点击Project Interpreter:New Virtualenv environment

3、安装所需的依赖包

两种方法:使用pycharm的project interpreter添加第三方库,使用命令行方式。

第一种方式适合新建的项目,逐渐的将自己需要的库文件完善,第二种方式适合有指导文档,一次将所有requirement安装。

方法一:该方法的好处是,不需要进入虚拟环境就可以将第三方库安装在工程里面,点击 '+' 添加即可。

图片.png

方法二:适合批量安装第三方库的情况:

进入工程的cmd 目录下:进入虚拟环境

图片.png

 

图片.png

 

进入虚拟环境:

图片.png

 

图片.png

查询当前虚拟环境的库安装情况:

 

升级pip及安装工具:

python -m pip install --upgrade pip

pip install --upgrade setuptools

基础包:

安装mysqlclient的时候会提示需要c++ 2014,需要将下载的whl文件放在requirements同一目录下。

图片.png

 

其他包需要在pycharm或者venv环境下安装,将requirements.txt放在Django的文件夹下:

requirements文件内容形式如下:

图片.png

 

(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip install -r requirements.txt

 

(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip install djangoCollecting django  Using cached https://files.pythonhosted.org/packages/eb/4b/743d5008fc7432c714d753e1fc7ee56c6a776dc566cc6cfb4136d46cdcbb/Django-2.2.2-py3-none-any.whlCollecting sqlparse (from django)  Using cached https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whlCollecting pytz (from django)  Using cached https://files.pythonhosted.org/packages/3d/73/fe30c2daaaa0713420d0382b16fbb761409f532c56bdcc514bf7b6262bb6/pytz-2019.1-py2.py3-none-any.whlInstalling collected packages: sqlparse, pytz, djangoSuccessfully installed django-2.2.2 pytz-2019.1 sqlparse-0.3.0You are using pip version 19.0.3, however version 19.1.1 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip listPackage    Version---------- -------Django     2.2.2pip        19.0.3pytz       2019.1setuptools 40.8.0sqlparse   0.3.0You are using pip version 19.0.3, however version 19.1.1 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip install pymysqlCollecting pymysql  Using cached https://files.pythonhosted.org/packages/ed/39/15045ae46f2a123019aa968dfcba0396c161c20f855f11dea6796bcaae95/PyMySQL-0.9.3-py2.py3-none-any.whlInstalling collected packages: pymysqlSuccessfully installed pymysql-0.9.3You are using pip version 19.0.3, however version 19.1.1 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip listPackage    Version---------- -------Django     2.2.2pip        19.0.3PyMySQL    0.9.3pytz       2019.1setuptools 40.8.0sqlparse   0.3.0You are using pip version 19.0.3, however version 19.1.1 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip install mysqlclient-1.4.2-cp37-cp37m-win32.whlRequirement 'mysqlclient-1.4.2-cp37-cp37m-win32.whl' looks like a filename, but the file does not existProcessing c:\python\django2_code\4_chapter\mydjango\mysqlclient-1.4.2-cp37-cp37m-win32.whlCould not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\python\\Django2_Code\\4_chapter\\MyDjango\\mysqlclient-1.4.2-cp37-cp37m-win32.whl'You are using pip version 19.0.3, however version 19.1.1 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip install mysqlclient-1.4.2-cp37-cp37m-win32.whlProcessing c:\python\django2_code\4_chapter\mydjango\mysqlclient-1.4.2-cp37-cp37m-win32.whlInstalling collected packages: mysqlclientSuccessfully installed mysqlclient-1.4.2You are using pip version 19.0.3, however version 19.1.1 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip listPackage     Version----------- -------Django      2.2.2mysqlclient 1.4.2pip         19.0.3PyMySQL     0.9.3pytz        2019.1setuptools  40.8.0sqlparse    0.3.0You are using pip version 19.0.3, however version 19.1.1 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.(venv) C:\python\Django2_Code\4_chapter\MyDjango>pip install mysql-connector-pythonCollecting mysql-connector-python  Downloading https://files.pythonhosted.org/packages/c5/40/c7ec860ad658870296c1a40afebce8e148997f6759d44307c7b6faa2b130/mysql_connector_python-8.0.16-py2.py3-none-any.whl (341kB)    100% |████████████████████████████████| 348kB 9.7kB/sCollecting protobuf>=3.0.0 (from mysql-connector-python)  Downloading https://files.pythonhosted.org/packages/60/17/74744dcf518e314d21dacdf0958ae80fe98b338e86e4d01e0d0e15697e46/protobuf-3.8.0-cp37-cp37m-win32.whl (888kB)    100% |████████████████████████████████| 890kB 14kB/sRequirement already satisfied: setuptools in c:\python\django2_code\4_chapter\mydjango\venv\lib\site-packages (from protobuf>=3.0.0->mysql-connector-python) (40.8.0)Collecting six>=1.9 (from protobuf>=3.0.0->mysql-connector-python)  Downloading https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whlInstalling collected packages: six, protobuf, mysql-connector-pythonSuccessfully installed mysql-connector-python-8.0.16 protobuf-3.8.0 six-1.12.0You are using pip version 19.0.3, however version 19.1.1 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.(venv) C:\python\Django2_Code\4_chapter\MyDjango>

 

4、创建超级用户及数据表(如使用默认数据库,可省略此步)

导入pymysql库

在/project_name/__init__.py中添加下面两行。注意不是app_name

import pymysql

pymysql.install_as_MySQLdb()

创建数据库(mysql已完成安装,且mysql已成为环境变量)

数据库名/用户名/密码。注意下面用户名和密码是本地已经设置的,源码中需要修改。数据库名需要创建。

/project_name/setting/ 中的DATABASES包含数据库的信息

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'mydjango',

        'USER': 'root',

        'PASSWORD': '20190124@ali',

        'HOST': '127.0.0.1',

        'PORT': '3306',

    },

}

命令行,创建数据库:

 

C:\Users\lanvis>mysql -u rootERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)C:\Users\lanvis>mysql -u root -pEnter password: ************Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 174Server version: 8.0.16 MySQL Community Server - GPLCopyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> create database mydjango;     #要特别注意要加上结束符;Query OK, 1 row affected (0.02 sec)#查看创建的数据库mysql> show databases;+--------------------+| Database           |+--------------------+| mydjango           || django_database    || information_schema || mysql              || performance_schema || sys                |+--------------------+6 rows in set (0.01 sec)mysql>

 

创建代码中的模型到数据库的表

在工程目录/project_name/app_name/models.py中已经创建了类。需要通过以下命令映射到数据库中。

如果数据库已经运行过下面的命令,则会在/project_name/app_name/migrations目录下产生0001_initial.py文件。

python manage.py makemigrations

python manage.py migrate

 

命令说明:

makemigrations指令用于将index所定义的模型生成0001_initial.py。

migrate指令根据脚本代码在目标数据库中生成相对应的数据表

创建超级用户

python manage.py createsuperuser

根据提示输入超级用户的用户名、邮箱、密码

此为admin界面的用户名和密码界面-位于数据库的auth_user表中。

 

5、启动项目

pycharm运行

不成功,原因是Django is not importable in this environment。

需要重新进行Django的导入。点开Default前的+,选择Django server。选择绿色的+,再次选择Django server。重新配置该界面。

图片.png图片.png

配置如下:

图片.png

命令行运行

进入虚拟环境,输入命令(不要在非虚拟环境下运行,会导致使用环境变量的python环境)

python manage.py runserver

运行成功

打开浏览器输入:http://127.0.0.1:8000/,可进入首页index

后台管理系统登录地址:http://127.0.0.1:8000/admin/,输入superuser的用户名、密码登陆(首次登陆在debug模式下,有可能会报csrf错误,刷新页面即可)

 

6、其他

 

如使用MySQL数据库,需要将settiongs.py文件中的82-93行修改为:

 

DATABASES = {

'default': {

# 'ENGINE': 'django.db.backends.sqlite3',

# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

'ENGINE': 'django.db.backends.mysql',

'NAME': 'test',       # 请换成自己的数据库名称

'USER': 'root',

'PASSWORD': '**',  # 请换成自己的密码

'HOST': '127.0.0.1',  # 如果不能连接,改成localhost

'POST': '3306',

}

}

二、git做代码版本控制,数据库备份二、git做代码版本控制,数据库备份

 上传的代码拉下来之后已经可以直接使用的和需要部署的步骤

预装python3

这个参考上面的安装即可。

预装pycharm

这个需要安装pro版本的,社区版不支持数据库

预装mysql

需要装8.0以上的mysql社区版即可

拉取代码

拉取的代码需要做一些检测。

1、测试第三方库的安装

requirements.txt中的库是否已经在虚拟环境安装。

 

第三库名称

作用

版本

asn1crypto (0.24.0)

cffi (1.12.3)

cryptography (2.7)

用于解析和序列化 ASN.1 结构的快速,纯 python 库

 

cffi

 

 

cryptography

 

 

django-js-asset (1.2.2)

django-mptt (0.10.0)

mysql-connector-python (8.0.16)

mysqlclient (1.4.2)

pip (9.0.1)

protobuf (3.8.0)

pycparser (2.19)

PyMySQL (0.9.3)

pyserial (3.4)

pytz (2019.1)

setuptools (28.8.0)

six (1.12.0)

sqlparse (0.3.0)

 

 

 

image.png

2、检查数据库的连接

  • 已有数据库
>>>C:\Users\lanvis>mysql -u root -pEnter password: ************Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 174Server version: 8.0.16 MySQL Community Server - GPLCopyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.>>>mysql> show databases;+--------------------+| Database           |+--------------------+| mydjango           || django_database    || information_schema || mysql              || performance_schema || sys                |+--------------------+6 rows in set (0.01 sec)mysql>

如果是老的环境,此时查询数据库是已存在的,若是新的环境查询是是没有mydjango这个数据库的。需要我们

  • 新建数据库

如下,创建数据库之后,再次查询数据库。mydjango数据库已存在。

mysql> show databases;+--------------------+| Database           |+--------------------+| information_schema || mysql              || performance_schema || sakila             || sys                || world              |+--------------------+6 rows in set (0.01 sec)mysql> create database mydjango;Query OK, 1 row affected (0.04 sec)mysql> show databases;+--------------------+| Database           |+--------------------+| information_schema || mydjango           || mysql              || performance_schema || sakila             || sys                || world              |+--------------------+7 rows in set (0.00 sec)mysql>

 

数据库表检查

1、模型和目标数据库关系

新的数据库(myDjango)中没有数据表,而Django中数据表只能通过模型创建,因为模型和目标数据库之间有自身的映射规则。这些规则在代码中实现。不需要自己在数据库中创建数据表。否则会导致模型和目标数据库之间无法建立通信。

创建数据库表//第一个指令是生成脚本,第二条指令是创建或更新数据表

python manage.py makemigrations

创建/更新数据库表命令:第一个指令是生成脚本;第二条指令是创建或更新数据表

2、重建数据库

error1:新搭建的数据库直接运行上面的命令会报错:报错显示在多个地方因为数据库表不存在而报错。

这是因为Django在在构建数据库列表,程序已经开始执行了。url.py文件首先查找资源,如未能找到所需表便会出现报错。

image.png

因此在重新构建数据库的时候要把项目和app中url.py的path全部注释掉。避免它的执行。

image.png

error2:

提示在urls的路径下handler404相关的错误。

在/project_name/project_name/urls.py中定义了如下:

导致报错,注释掉本文件中的url后,再注释掉以下的这些代码。

# 设置404、500错误状态码# from index import views# handler404 = views.page_not_found# handler500 = views.page_not_found

 

image.png

 

创建超级用户

新数据库,超级用户需要重新创建。

创建的超级用户信息会保存在数据表auth_user中。

image.png

项目启动

将重建数据库时注释的path都恢复。

进入虚拟环境,输入命令(不要在非虚拟环境下运行,会导致使用环境变量的python环境)

python manage.py runserver

项目启动中的错误

error1:handler404的参数错误

ERRORS:?: (urls.E007) The custom handler404 view 'index.views.page_not_found' does not take the correct number of arguments (request, exception).

Django版本原因导致的问题。2.2版本需要将exception写入参数。

#2.0版本写法def page_not_found(request):    return render(request, 'error404.html', status=404)#2.2版本写法def page_not_found(request,exception=404):     return render(request, 'error404.html')

 

error2

STATICFILES_DIRS的地址没有包含STATIC_ROOT。

ERRORS:?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting.

这个可能也是版本导致的问题,也可能是语法的错误

 

STATIC_ROOT = os.path.join(BASE_DIR, 'static').replace('\\', '/')STATIC_URL = '/static/'# STATICFILES_DIRS用于收集admin的静态资源文件STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static/'),]#源代码没有/导致报错。#STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]

error3:找不到静态资源

项目在debug模式和线上模式是不一样的。

debug模式下Django本身提供静态资源服务,方便开发者开发网站的功能。

而该功能关闭后,需要由服务器完成该服务。

因此需要搜集下静态资源

(venv) C:\python\python_code\chapter_11\music>python manage.py collectstaticYou have requested to collect static files at the destinationlocation as specified in your settings:    C:\python\python_code\chapter_11\music\staticThis will overwrite existing files!Are you sure you want to do this?Type 'yes' to continue, or 'no' to cancel: yesFound another file with the destination path 'admin\css\autocomplete.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.Found another file with the destination path 'admin\css\base.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.Found another file with the destination path 'admin\css\changelists.css'. It will be ignored since only thefirst encountered file is collected. If this is not what you want, make sure every static file has a uniquepath.………………………………………………………………Found another file with the destination path 'admin\js\vendor\xregexp\xregexp.js'. It will be ignored sinceonly the first encountered file is collected. If this is not what you want, make sure every static file hasa unique path.Found another file with the destination path 'admin\js\vendor\xregexp\xregexp.min.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static filehas a unique path.5 static files copied to 'C:\python\python_code\chapter_11\music\static', 181 unmodified.(venv) C:\python\python_code\chapter_11\music>

 

当python manage.py runserver命令出现如下显示的时候。项目启动成功。

image.png

此时打开浏览器输入:http://127.0.0.1:8000/admin,进入管理界面。

完成代码的管理和使用。

pycharm上调试运行代码

参考本文的pycharm运行。

 

 

 

 

转载地址:https://blog.csdn.net/louniuous/article/details/105852997 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:android测试工具之monkey
下一篇:git 常用

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月07日 16时24分55秒