django_pycharm社区版开发记录1
新建项目
新建项目,使用虚拟环境。
完成后,是一个空项目:
使用Django框架
两个方法,方法1:在terminal输入命令pip install django,如果你没有换源,这个方法会很慢。我们用第2个方法;
方法2:打开setting对话框,选择Project Interpreter,如果右边有Django了就不管,如果没有,就点右边的"+“号
弹出对话框
输入django,如果这里只出现1行,或者没有搜索到,那么点击”Manage Repositories"设置源仓库:
输入新的源仓库地址,上面这些国内使用这几个源是没问题的。换源后返回上一个对话框,选中django,再点击“install Package”,开始安装。安装结束后。可以在terminal中用命令行检查:
(venv) D:\PythonWorkSpace\testgoogle>pip list
Package Version
---------- -------
asgiref 3.2.10
Django 3.0.7
pip 10.0.1
pytz 2020.1
setuptools 39.1.0
sqlparse 0.3.1
此时,Django的开发环境基本就安装好了。
第一个Django项目
以后凡是要输入命令的地方,均是在Terminal中进行,输入命令:Django-admin startproject mypro,建立自己的项目,命令结束后生成Django的目录结构:
具体每个文件的作用暂时不管,我们要建立自己的第1个应用,进入mypro目录:
(venv) D:\PythonWorkSpace\testgoogle>cd mypro
(venv) D:\PythonWorkSpace\testgoogle\mypro>python manage.py startapp myapp1
项目目录变成这样。
设置应用和项目
应用注入项目
项目目录下的settings.py文件中,INSTALLED_APPS段中加入一行应用名字
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp1',
]
注入临时目录
在项目根目录下新建目录template作为临时文件目录,并设置settings.py中的TEMPLATES段中修改DIRS:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
注入静态文件目录
在项目根目录下新建static目录,并注入到settings.py中:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static')
)
设置网页中文环境和时区
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
启动
输入命令:python manage.py runserver
(venv) D:\PythonWorkSpace\testgoogle\mypro>python manage.py runserver
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.
June 29, 2020 - 14:03:53
Django version 3.0.7, using settings 'mypro.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
在浏览器中输入http://127.0.0.1:8000/,出现小火箭就OK了。