文章目录
一、创建应用user
前提:在 luffy 虚拟环境下
# 1.终端从项目根目录进入apps目录
cd luffyapi & cd apps
# 2.创建app
python ../../manage.py startapp user
二. 创建User表对应的model:user/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
mobile = models.CharField(max_length=11, unique=True)
# 需要pillow包的支持
icon = models.ImageField(upload_to='icon', default='icon/default.png')
class Meta:
db_table = 'luffy_user'
verbose_name = '用户表'
verbose_name_plural = verbose_name
def __str__(self):
return self.username
- 下载pillow模块
pip install pillow
三、注册应用配置User表
1.注册应用
- dev.py文件
INSTALLED_APPS = [
...
'rest_framework',
'user',
]
2.配置User表
# 指定自定义的表 : [应用名.表名]
AUTH_USER_MODEL = 'user.User'
四、配置media
1.media路径配置
- 在dev.py文件
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
2. media目录(提示:不用配置,上传文件时会自动生成)
├── luffyapi
└── luffyapi/
└── media/
└── icon
└── default.png
五、路由配置
1.主路由配置luffyapi/urls.py:
from django.contrib import admin
from django.urls import path, re_path, include
from django.views.static import serve
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('user/', include('user.urls')),
re_path('^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT})
]
2.子路由配置 : user/urls.py
from django.urls import path, include
from rest_framework.routers import SimpleRouter
router = SimpleRouter
# 注册ViewSet的路由
# router.register()
urlpatterns = [
path('', include(router.urls)),
]
六.进行数据库迁移
- cd 到项目根路径下, 因为 manage.py 在项目根路径下
python manage.py makemigrations
python manage.py migrate