下载Python,最新的版本3.7.4,官方下载大约25M会比较慢,需要耐心等待,官方要下载这个版本:Windows x86-64 executable installer。
官网下载地址:https://www.python.org/downloads/release/python-374/
官方地址:https://www.djangoproject.com/download/
安装方式:使用管理员权限运行CMD,然后粘贴如下命令回车,等待安装完成即可。pip是python的包安装程序,类似于.Net的NuGet
pip install Django==3.0.6
Collecting Django==3.0.6
Downloading https://files.pythonhosted.org/packages/9d/04/04abb097c84c770180eeebe7ed920ce42f9917ab5ad4de01ff8ed11bc25b/Django-3.0.6-py3-none-any.whl (7.5MB)
|▌ | 122kB 12kB/s eta 0:09:52
安装过程中你可能会遇到版本问题:直接使用提示上的命令,更新版本即可。
python -m pip install --upgrade pip
比如下面这个异常
pip install Django==3.0.6
Collecting Django==3.0.6
Downloading https://files.pythonhosted.org/packages/9d/04/04abb097c84c770180eeebe7ed920ce42f9917ab5ad4de01ff8ed11bc25b/Django-3.0.6-py3-none-any.whl (7.5MB)
|██ | 481kB 5.6kB/s eta 0:20:47ERROR: Exception:
Traceback (most recent call last):
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 425, in _error_catcher
yield
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 507, in read
data = self._fp.read(amt) if not fp_closed else b""
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read
data = self.__fp.read(amt)
File "d:\program files (x86)\python38-32\lib\http\client.py", line 454, in read
n = self.readinto(b)
File "d:\program files (x86)\python38-32\lib\http\client.py", line 498, in readinto
n = self.fp.readinto(b)
File "d:\program files (x86)\python38-32\lib\socket.py", line 669, in readinto
return self._sock.recv_into(b)
File "d:\program files (x86)\python38-32\lib\ssl.py", line 1241, in recv_into
return self.read(nbytes, buffer)
File "d:\program files (x86)\python38-32\lib\ssl.py", line 1099, in read
return self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\cli\base_command.py", line 153, in _main
status = self.run(options, args)
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 382, in run
resolver.resolve(requirement_set)
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\legacy_resolve.py", line 201, in resolve
self._resolve_one(requirement_set, req)
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\legacy_resolve.py", line 365, in _resolve_one
abstract_dist = self._get_abstract_dist_for(req_to_install)
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\legacy_resolve.py", line 312, in _get_abstract_dist_for
abstract_dist = self.preparer.prepare_linked_requirement(
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\operations\prepare.py", line 191, in prepare_linked_requirement
unpack_url(
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\download.py", line 459, in unpack_url
unpack_http_url(
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\download.py", line 312, in unpack_http_url
from_path, content_type = _download_http_url(link,
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\download.py", line 551, in _download_http_url
_download_url(resp, link, content_file, hashes, progress_bar)
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\download.py", line 253, in _download_url
hashes.check_against_chunks(downloaded_chunks)
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\utils\hashes.py", line 80, in check_against_chunks
for chunk in chunks:
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\download.py", line 223, in written_chunks
for chunk in chunks:
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\utils\ui.py", line 160, in iter
for x in it:
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_internal\download.py", line 188, in resp_read
for chunk in resp.raw.stream(
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 564, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 529, in read
raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
File "d:\program files (x86)\python38-32\lib\contextlib.py", line 131, in __exit__
self.gen.throw(type, value, traceback)
File "d:\program files (x86)\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 430, in _error_catcher
raise ReadTimeoutError(self._pool, None, "Read timed out.")
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.
WARNING: You are using pip version 19.3.1; however, version 20.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
python -m pip install --upgrade pip
Collecting pip
Downloading https://files.pythonhosted.org/packages/54/2e/df11ea7e23e7e761d484ed3740285a34e38548cf2bad2bed3dd5768ec8b9/pip-20.1-py2.py3-none-any.whl (1.5MB)
|████████████████████████████████| 1.5MB 29kB/s
Installing collected packages: pip
Found existing installation: pip 19.3.1
Uninstalling pip-19.3.1:
Successfully uninstalled pip-19.3.1
Successfully installed pip-20.1
再次安装Django
pip install Django==3.0.6
Collecting Django==3.0.6
Downloading Django-3.0.6-py3-none-any.whl (7.5 MB)
|████████████████████████████████| 7.5 MB 23 kB/s
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/pytz/
Collecting pytz
Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB)
|████████████████████████████████| 510 kB 13 kB/s
Collecting sqlparse>=0.2.2
Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB)
|████████████████████████████████| 40 kB 18 kB/s
Collecting asgiref~=3.2
Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB)
Installing collected packages: pytz, sqlparse, asgiref, Django
Successfully installed Django-3.0.6 asgiref-3.2.7 pytz-2020.1 sqlparse-0.3.1
以上Django的环境就已经搭建好了,剩下的就是使用VS2019新建Django的项目了,如果当时没有安装Python的开发环境,那么使用Visual Studio Installer重新勾上Python即可。
让后搜素Python选择Django Web
项目名称
目录接口如下
简单粗暴就直接在项目上右键 ---调试--启动新实例
然后会在弹出控制台相关信息
当然你也可以控制台命令启动项目,cmd 命令 cd到项目目录下面,然后执行启动
python manage.py runserver
我们可以看到 端口是58223,访问路径 http://127.0.0.1:58223/,web就可以运行调试了
Performing system checks...
System check identified no issues (0 silenced).
You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth.
Run 'python manage.py migrate' to apply them.
May 14, 2020 - 21:56:26
Django version 3.0.6, using settings 'vs2019_python_django_docker.settings'
Starting development server at http://127.0.0.1:58223/
Quit the server with CTRL-BREAK.
在浏览器 中 访问 http://127.0.0.1:58223/
抛异常了,告诉自己没有事呀没有事...........
在urls.py这个文件中 有相关路径的设置
看到了一个admin
试一试,访问下 http://localhost:58223/admin,可以访问了,项目是正常的
but要用户名和密码??Right-click the project node and select Python->Django Create Superuser. 已提示我们!
创建超级用户 输入超级用户名 administrator ,回车
输入邮箱 回车,密码,确认密码回车
Python 3.8 (32-bit) 交互窗口 [PTVS 16.4.19310.1-16.0]
键入 $help 获取命令列表。
正在执行 manage.py createsuperuser
You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth.
Run 'python manage.py migrate' to apply them.
Username (leave blank to use 'administrator'):
administrator
Email address:
[email protected]
D:\Program Files (x86)\Python38-32\lib\getpass.py:100: GetPassWarning: Can not control echo on the terminal.
return fallback_getpass(prompt, stream)
Warning: Password input may be echoed.
Password:
123456
Warning: Password input may be echoed.
Password (again):
123456
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]:
y
Superuser created successfully.
交互 Python 进程已退出。
交互 Python 进程已退出。
再次启动调试,登陆时输入刚刚设置的用户名和密码
5.1 Dockerfile内容
FROM python:3.8
RUN python -m pip install --upgrade pip
COPY app /home/vs2019_python_django_docker/app
#COPY static /home/vs2019_python_django_docker/static
COPY run.sh /home/vs2019_python_django_docker/run.sh
COPY vs2019_python_django_docker /home/vs2019_python_django_docker/vs2019_python_django_docker
COPY db.sqlite3 /home/vs2019_python_django_docker/db.sqlite3
COPY manage.py /home/vs2019_python_django_docker/manage.py
ADD Django-3.0.6.tar.gz /usr/local/src
WORKDIR /usr/local/src/Django-3.0.6
RUN python setup.py install
WORKDIR /home/vs2019_python_django_docker
CMD ["/bin/bash", "run.sh"]
5.2 docker-compose.yaml内容
version: '2'
services:
vs2019pythondjangodocker:
build: #镜像构建
context: . #构建镜像时所在的资源路径
dockerfile: Dockerfile #构建镜像时需要的dockerfile文件路径
ports:
- "9999:80" #端口映射
image: vs2019pythondjangodocker:v1.0 #镜像名称和tag
5.3 run.sh内容
python manage.py runserver 0.0.0.0:80 --noreload --settings vs2019_python_django_docker.settings
启动
docker-compose -f docker-compose.yaml up --build -d
查看镜像
# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
vs2019pythondjangodocker v1.0 1bae576703c3 12 minutes ago 1.04GB
查看启动的容器
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0256608f62a0 vs2019pythondjangodocker:v1.0 "/bin/bash run.sh" 13 minutes ago Up 13 minutes 0.0.0.0:9999->80/tcp vs2019-python-django-docker_vs2019pythondjangodocker_1
停止
docker-compose -f docker-compose.yaml down
7.1 DisallowedHost at /admin【已解决】
Invalid HTTP_HOST header: '192.168.134.139:9999'. You may need to add '192.168.134.139' to ALLOWED_HOSTS.
修改 setting.py 文件:
ALLOWED_HOSTS = ['*'] #在这里请求的host添加了*
7.2 在构建镜像时 安装Django 很慢(网络影响),需要等很久【未解决】
7.3 登录提示 Forbidden (403) 【已解决】 (vs中调试正常,在linux中docker部署后访问点击登录就会有这个提示)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.
Reason given for failure:
CSRF cookie not set.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
request
to the template's render
method.{% csrf_token %}
template tag inside each POST form that targets an internal URL.CsrfViewMiddleware
, then you must use csrf_protect
on any views that use the csrf_token
template tag, as well as those that accept the POST data.You're seeing the help section of this page because you have DEBUG = True
in your Django settings file. Change that to False
, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
这个问题想了一宿,于是我决定看看容器日志
docker logs 0256608f62a0 -f
这一看,我明白了。
Forbidden (CSRF cookie not set.): /admin/login/
[17/May/2020 07:36:20] "POST /admin/login/?next=/admin/ HTTP/1.1" 403 2864
Forbidden (CSRF cookie not set.):Internal Server Error: /
原来浏览器cookie 有异常(QQ浏览器害人),将其换为google浏览器内核,或者换成google浏览器试试,正常!
这样就没问题。
网上看了QQ浏览器开cookie 的方式,感觉莫名的一团雾水。