创建User表,路由配置

user模块User表

创建user模块

1
2
3
4
5
6
7
前提:在 luffy 虚拟环境下

1.终端从项目根目录进入apps目录
>: cd luffyapi & cd apps

2.创建app
>: python ../../manage.py startapp user

创建User表对应的model:user/models.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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')

classMeta:
db_table = 'luffy_user'
verbose_name = '用户表'
verbose_name_plural = verbose_name

def__str__(self):
return self.username

数据库相关模型models中写上image字段其中的一些属性可以帮助更好的标记文件,更好的跟踪文件上传。
比如:%Y代表年,%m代表月,blank=True代表可以为空。当上传文件时,代表上传到image目录下,以当前年月子目录的文件夹中。gpic = models.ImageField(verbose_name="图片路径", default="image/default.png", upload_to='df_goods/image/%Y/%m', null=True, blank=True) # 商品图片

 

注册user模块,配置User表:dev.py

1
2
3
4
5
6
7
INSTALLED_APPS = [
# ...
'user',
]

# 自定义User表
AUTH_USER_MODEL = 'user.User'

配置media

media配置:dev.py
1
2
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
media目录配置
1
2
3
4
5
6
7
"""
├── luffyapi
└── luffyapi/
└── media/
└── icon
└── default.png
"""
主路由:luffyapi/urls.py
1
2
3
4
5
6
7
8
9
10
11
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}) # 暴露资源给外界
]
子路由:user/urls.py
1
2
3
4
5
6
7
8
9
from django.urls import path, include
from utils.router import router

# 注册ViewSet的路由
# router.register()

urlpatterns = [
path('', include(router.urls)),
]

数据库迁移

1
2
3
4
5
6
7
8
9
10
"""
1)去向大luffyapi所在目录的终端

2)安装pillow模块
pip install pillow

3)数据库迁移
python manage.py makemigrations
python manage.py migrate
"""

posted on 2020-12-04 11:15  Plyc  阅读(264)  评论(0编辑  收藏  举报

导航