Django自定义用户不能使用自定义用户的信号

drnojrws  于 2022-12-05  发布在  Go
关注(0)|答案(2)|浏览(176)

查看自定义用户和用户配置文件

class Users(AbstractUser):
    username = None
    email = models.EmailField(unique=True, null=False, db_column='email')
    is_staff = models.BooleanField(default=False, db_column='is_staff')
    is_active = models.BooleanField(default=False, db_column='is_active')
    date_joined = models.DateTimeField(default=timezone.now, db_column='date_joined')
    updated_at = models.DateTimeField(auto_now=True, auto_now_add=False, db_column='updated_at')

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    objects = UsersManager()

    def __str__(self):
        return self.email

    class Meta:
        db_table = 'mn_users'
        verbose_name = 'user'
        verbose_name_plural = 'users'

class UserProfiles(models.Model):
    user_profile_id = models.AutoField(primary_key=True, db_column='user_profile_id')
    user_id = models.OneToOneField('Users', on_delete=models.CASCADE, db_column='user_id')
    photo = CloudinaryField('image')
    msisdn = models.CharField(max_length=12, null=True, blank=True, unique=True, db_column='msisdn')
    nationality_id = models.ForeignKey(Nationalities, related_name='nationalites2userprofiles', null=True, blank=True, on_delete=models.PROTECT, db_column='nationality_id')
    language_id = models.ForeignKey(Languages, related_name='preferred_languages2users', null=True, blank=True, on_delete=models.PROTECT, db_column='language_id')
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True, db_column='created_at')
    updated_at = models.DateTimeField(auto_now=True, auto_now_add=False, db_column='updated_at')

    def __str__(self):
        return self.role_id

    class Meta:
        db_table = 'mn_user_profiles'
        verbose_name = 'user_profile'
        verbose_name_plural = 'user_profiles'

所以我使用Django rest框架来创建用户,并且运行正常。问题是我希望在创建用户时创建一个用户配置文件。为此,我在users/ www.example.com中创建了一个信号文件signals.py

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

from .models import Users, UserProfiles

@receiver(post_save, sender=Users)
def create_profile(sender, instance, created, **kwargs):
    if created:
        UserProfiles.objects.create(users=instance)

@receiver(post_save, sender=Users)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

然后,我将上述内容添加到users/app.py

from django.apps import AppConfig

class UsersConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'users'

class UserProfileConfig(AppConfig):
    name = 'UserProfiles'

    def ready(self):
        import users.signals

在我安装的应用程序中,我将用户应用程序称为用户应用程序
'用户.应用程序.用户配置',
我已经宣布我的
AUTH_USER_MODEL =“用户.用户”。
那么这里的问题是什么呢?它很好地插入了用户,但是没有创建用户配置文件。我也在djangorest框架中使用了djoser

6mzjoqzu

6mzjoqzu1#

我发现了问题您需要在www.example.com文件中包含信号URLs.py

4c8rllxm

4c8rllxm2#

在urls.py:

from .signals import *

相关问题