官术网_书友最值得收藏!

Signals

Ideally, every time a user model instance is created, a corresponding user profile instance must be created as well. This is usually done using signals.

For example, we can listen for the post_save signal from the user model using the following signal handler in profiles/signals.py:

from django.db.models.signals import post_save 
from django.dispatch import receiver 
from django.conf import settings  
from . import models 
 
@receiver(post_save, sender=settings.AUTH_USER_MODEL) 
def create_profile_handler(sender, instance, created, **kwargs): 
    if not created: 
        return 
    # Create the profile object, only if it is newly created 
    profile = models.Profile(user=instance) 
    profile.save() 

The profile model has passed no additional initial parameters except for the user=instance.

Previously, there was no specific place for initializing the signal code. Typically, they were imported or implemented in models.py (which was unreliable). However, with app-loading refactor in Django 1.7, the application initialization code location is well defined.

First, subclass the ProfileConfig method in apps.py within the profiles app and set up the signal in the ready method:

# apps.py 
from django.apps import AppConfig 
 
class ProfilesConfig(AppConfig): 
    name = "profiles" 
    verbose_name = 'User Profiles' 
 
    def ready(self): 
        from . import signals 

Next, change the line mentioning profiles in your INSTALLED_APPS to a dotted path pointing to this AppConfig. So your settings should look as follows:

INSTALLED_APPS = [
'profiles.apps.ProfilesConfig',
'posts',
...

With your signals set up, accessing user.profile should return a Profile object to all users, even the newly created ones.

主站蜘蛛池模板: 通江县| 紫阳县| 宣威市| 杭锦后旗| 辽宁省| 兴仁县| 商河县| 洛川县| 喀喇沁旗| 凌云县| 罗田县| 留坝县| 磴口县| 绥中县| 莱西市| 双柏县| 曲周县| 乌兰察布市| 呼图壁县| 紫金县| 大关县| 武夷山市| 偃师市| 盘山县| 蓬安县| 龙口市| 临夏市| 岑溪市| 会宁县| 寿光市| 蒙山县| 灌阳县| 平乐县| 伊通| 花莲县| 班玛县| 龙陵县| 格尔木市| 巩留县| 贺兰县| 商城县|