首页 > 后端开发 > Python教程 > Django教程中User-Profile的使用方法介绍(附源码)

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

不言
发布: 2018-09-15 14:23:56
原创
2450 人浏览过

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

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

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

on_delete=models.CASCADE
登录后复制

引入与信号相关的包

from django.dispatch import receiverfrom django.db.models.signals import post_save
登录后复制

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

源码

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的使用方法介绍(附源码)的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
python - django'没有名为'mdx_markwdown'的模块
来自于 1970-01-01 08:00:00
0
0
0
python - Django 模型foreignKey 参考
来自于 1970-01-01 08:00:00
0
0
0
angular.js - angularjs和django结合的问题
来自于 1970-01-01 08:00:00
0
0
0
解决Django中的django.db.utils.NotSupportedError错误
来自于 1970-01-01 08:00:00
0
0
0
wsgi - apache和django之间如何调用
来自于 1970-01-01 08:00:00
0
0
0
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板