django 项目初始化
创建项目、应用、用户
django-admin startproject xxx
python manage.py startapp book
python manage.py createsuperuser
创建应用后,需要到setting.py中去注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book'
]
设置语言和时区
通过在settings.py中通过设置
- LANGUAGE_CODE来设置语言
- zh_Hans代表中文简体
- zh_Hant代表中文繁体
- TIME_ZONE设置时区
设置数据库
在setting.py文件中设置连接的数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'xxx',
'HOST':'localhost',
'PORT':'3306',
'USER':'username',
'PASSWORD':'password'
}
}
在项目的init.py文件中添加
import pymysql
pymysql.install_as_MySQLdb()
静态文件、模板路径设置
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
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',
],
},
},
]
ALLOWED_HOSTS = ['*']
替换系统User
编写模型,继承AbstractUser,自定义字段
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""
用户
"""
name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
birthday = models.DateField(null=True, blank=True, verbose_name="出生年月")
gender = models.CharField(max_length=6, choices=(("male", u"男"), ("female", "女")), default="female", verbose_name="性别")
mobile = models.CharField(null=True, blank=True, max_length=11, verbose_name="电话")
email = models.EmailField(max_length=100, null=True, blank=True, verbose_name="邮箱")
class Meta:
verbose_name = "用户"
verbose_name_plural = verbose_name
def __str__(self):
return self.username
最后,在setting.py中添加,替换默认模型
AUTH_USER_MODEL = "book.User"
管理站点添加模型
在应用下admin.py中注册模型到管理站点
from django.contrib import admin
from book.models import User
admin.site.register(User)
数据库迁移命令
python manage.py makemigrations
python manage.py migrate
DRF
这里是drf的官方文档
安装DRF
直接安装
pip install djangorestframework
安装后,在setting.py里面注册应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book',
'rest_framework',
]
|