创建项目
django-admin startproject 项目名
创建app
python manage.py startapp app名
启动Django 浏览器输入网址127.0.0.1:8000 默认端口号为8000
python manage.py runserver
修改Django默认的端口
python manage.py runserver 端口号
修改ip地址
python manage.py runserver ip地址
setting配置
Django静态文件配置
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
templates配置
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',
],
},
},
]
将APP添加至项目
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'yingmo'#app名称
]
models
python manage.py makemigrations
数据库迁移命令
D:\djngo project\momo>python manage.py makemigrations
Migrations for 'yingmo':
yingmo\migrations\0001_initial.py
- Create model user
D:\djngo project\momo>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, yingmo
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
Applying yingmo.0001_initial... OK
D:\djngo project\momo>
使用mysql数据库
1.修改settings下的数据库
import pymsql
pymysql.install_asMySQLdb()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '数据库名',
'HOST':'127.0.0.1',
'PORT':3306,
'USER':'root',
'PASSWORD':'root'
}
}
import pymysql
pymysql.install_as_MySQLdb()
通常写在
2.在APP下的models.py写model
3.执行数据库迁移命令
python manage.py makemigrations
python manage.py migrate
同SQLLITE一样
4.使用时出现错误
这是mysql 和Django版本不一致导致的,之前使用的是Django3.1 MySQL5.0
此时使用Django2.0和mysql8.0版本得以解决