创建Django项目

个人推荐使用Pycharm社区版

创建Django项目

若出现报错,报错如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Traceback (most recent call last):
File "D:/Django/mysite1/manage.py", line 22, in <module>
main()
File "D:/Django/mysite1/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "D:\Django\mysite1\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\Django\mysite1\venv\lib\site-packages\django\core\management\__init__.py", line 325, in execute
settings.INSTALLED_APPS
File "D:\Django\mysite1\venv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__
self._setup(name)
File "D:\Django\mysite1\venv\lib\site-packages\django\conf\__init__.py", line 66, in _setup
self._wrapped = Settings(settings_module)
File "D:\Django\mysite1\venv\lib\site-packages\django\conf\__init__.py", line 157, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Users\10938\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\Django\mysite1\mysite1\settings.py", line 58, in <module>
'DIRS': [os.path.join(BASE_DIR, 'templates')]
NameError: name 'os' is not defined

解决方案:在settings.py中导入 os 模块

打开Terminal,运行django项目 python manage.py runserver

Django项目运行

更换端口号python manage.py runserver 5000

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(venv) D:\Django\mysite1>python manage.py runserver 5000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
Jun 27, 2022 - 07:50:30
Django version 2.2.12, using settings 'mysite1.settings'
Starting development server at http://127.0.0.1:5000/
Quit the server with CTRL-BREAK.


如果启动出现了端口占用,可以这样做:

端口占用

项目结构

项目结构

1.db.sqlite3文件:项目首次运行后生成的文件,是Django的默认数据库

2.manage.py文件:命令存储:

manage.py

3.项目的同名文件夹:

项目同名

sttings.py配置文件

settings配置

DEBUG=True

启动模式

①True - 调试模式
检测代码改动后,立刻重启服务;报错页面

②False - 正式启动模式/上线模式;出错了不会进行多余提示,只会告诉你错了

ALLOWED_HOSTS = [] 请求头HOST,主要在项目上线后的过滤访问

Allowed_host

在虚拟机上启动项目,然后使用我们的Windows去访问,需要将内网IP添加到ALLOWED_HOSTS中。

ROOT_URLCONF = ‘testdjango1.urls’

语言设置,改成中文且要修改时区

LANGUAGE_CODE = ‘zh-Hans’
TIME_ZONE = ‘Asia/Shanghai’

chinesedjango

小总结