Django教程中User-Profile的使用方法介绍(附源码)


本文摘自php中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于Django教程中User-Profile的使用方法介绍(附源码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

Profile作用:User内置的字段不够完善,导致创建的用户信息单一,Profile就是为了对User进行扩展,即丰富用户信息

在models中创建Profile类,添加字段user与User形成OneToOne关系以及级联删除

1

on_delete=models.CASCADE

引入与信号相关的包

1

from django.dispatch import receiverfrom django.db.models.signals import post_save

装饰器装饰函数,User创建时信号触发自动创建Profile的user字段并关联;User保存时信号触发,Profile自动保存

源码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

from django.db import models

from django.contrib.auth.models import User

#信号

from django.db.models.signals import post_save,post_init

from django.dispatch import receiver

class Profile(models.Model):

    user = models.OneToOneField(User,on_delete=models.CASCADE)

    birth = models.DateField(null=True,blank=True)

    def __str__(self):

        return self.user.username

    class Meta:

        db_table = 'profile'

@receiver(post_save,sender=User)

def create_user_profile(sender,instance,created,**kwargs):

    print('创建User')

    if created:

        Profile.objects.create(user=instance)

@receiver(post_save,sender=User)

def save_user_profile(sender,instance,**kwargs):

    print('保存User')

    instance.profile.save()

相关推荐:

在Django的session中使用User对象的方法

五步教你实现使用Nginx+uWSGI+Django方法部署Django程序

以上就是Django教程中User-Profile的使用方法介绍(附源码)的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python中的os模块

Python编译器和解释器的区别

Python爬虫是干什么的

Python是面向对象还是面向过程的

Python全栈是什么意思

Python抽象类有什么用

Python环境变量如何配置

Python配置mysql的教程(必看)

简要概括Python if多条件判断语句的特点

Python怎么计算加减乘除

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...