Introduction to the use of User-Profile in Django tutorial (source code attached)

不言
Release: 2018-09-15 14:23:56
Original
2343 people have browsed it

This article brings you an introduction to the use of User-Profile in the Django tutorial (source code attached). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Profile function: The built-in fields of User are not perfect enough, resulting in a single user information. Profile is to extend User, that is, to enrich user information.

Create a Profile class in models and add fields. User forms a OneToOne relationship with User and cascade deletion

on_delete=models.CASCADE
Copy after login

Introduces signal-related packages

from django.dispatch import receiverfrom django.db.models.signals import post_save
Copy after login

Decorator Decoration function, the signal is triggered when the User is created, and the user field of the Profile is automatically created and associated; the signal is triggered when the User is saved, and the Profile is automatically saved

Source code

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()
Copy after login

Related recommendations:

How to use the User object in Django’s session

Five steps to teach you how to deploy using Nginx uWSGI Django method Django program

The above is the detailed content of Introduction to the use of User-Profile in Django tutorial (source code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template