Loading

创建User表

继承AbstractUser

from django.db import models

# Create your models here.
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    # 拓展手机号
    phone = models.CharField(max_length=11, verbose_name='手机号码')
    # 拓展头像 设置头像上传地址, 默认头像
    icon = models.ImageField(upload_to='icon', default='icon/default.png')

配置文件中, 设置媒体文件路径

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

开发媒体文件的访问

from django.contrib import admin
from django.urls import path, re_path
# 导入serve视图类
from django.views.static import serve
# 导入内置配置文件, 会自动到dev.py配置文件中去查询
from django.conf import settings
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT})
]

头像上传依赖Pillow模块

pip install Pillow

配置使用自己定义的user表

# 'app.表名'
AUTH_USER_MODEL = 'user.user'

执行数据库迁移命令

python manage.py makemigrations
python manage.py migrate

在luffy项目主应用中创建media/icon目录, 添加一个默认头像

image

image

创建用户表, 先不继承AbstractUser

from django.db import models

class User(models.Model):
    # 拓展手机号
    phone = models.CharField(max_length=11, verbose_name='手机号码')
    # 拓展头像 设置头像上传地址, 默认头像
    icon = models.ImageField(upload_to='icon', default='icon/default.png')

执行数据库迁移命令

PS F:\synchro\Project\luffy> python manage.py makemigrations
You are trying to add a non-nullable field 'password' to user without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option:


您正在尝试向用户添加一个不可为空的字段“password”,而没有默认值;我们不能这样做(数据库需要一些东西来填充现有的行)。
请选择修复程序:
1) 现在提供一个一次性默认值(将在所有现有行上设置此列的空值)
2) 退出,让我在模型中添加一个默认值

数据库迁移过早

用户表基于内置auth的user表.
注意: 在继承该表之前执行过数据库迁移命令, 后期想继承该表, 需要把所有app下的迁移文件删除, 之后删除库中表.
1. 删除 admin, auth, 自定义的app下的migrate文件的迁移文件, __init__.py 不能删除!
    from django.contrib import admin
    from django.contrib import auth
2. 删库使用Navicat Premium 将数据库的文件保存好, 再删除表文件重新执行数据库迁移命令!

image

image

image

image

image

再重新执行数据库迁移

python manage.py makemigrations
python manage.py migrate

启动项目, 测试媒体文件开发

http://127.0.0.1:8000/media/icon/default.png

posted @ 2022-11-30 23:43  爱learn  阅读(97)  评论(0编辑  收藏  举报