1. 程式人生 > 其它 >5.建立app、建立user表、配置media、資料遷移

5.建立app、建立user表、配置media、資料遷移

user模組User表

建立user模組

前提:在 luffy 虛擬環境下

1.終端從專案根目錄進入apps目錄
>: cd luffyapi & cd apps

2.建立app
先切換到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

註冊user模組,配置User表:dev.py

# 註冊
INSTALLED_APPS = [
    # ...
    'user',
]

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

配置media

media配置:dev.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
media目錄配置
"""
├── luffyapi
    └──	luffyapi/
       	└──	media/  	
			└──	icon 
				└── default.png
"""
主路由: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})
]
子路由:user/urls.py
from django.urls import path, include
from utils.router import router

# 註冊ViewSet的路由
# router.register()

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

資料庫遷移

"""
1)去向大luffyapi所在目錄的終端

2)安裝pillow模組
pip install pillow

3)資料庫遷移
python manage.py makemigrations
python manage.py migrate
"""