简体   繁体   English

Django:带有扩展用户模型的信号

[英]Django : Signals with a extend User model

I am in Django 1.11 and my question is quite simple : 我在Django 1.11中,我的问题很简单:
I read these posts : 我读了这些帖子:

and I am not sure a StudentCollaborator user will be created/updated when a user exists (there is already users in the database so I cannot simply redo stuff ). 而且我不确定当一个用户存在时会创建/更新一个StudentCollaborator用户(数据库中已经有用户,所以我不能简单地重做东西)。

My current code looks like this : 我当前的代码如下所示:

# Create your models here.
class StudentCollaborator(models.Model):
    #  https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    """" code postal : pour l'instant que integer"""
    code_postal = models.IntegerField(null=True, blank=False)
    """" flag pour dire si l'user a activé le système pour lui """
    collaborative_tool = models.BooleanField(default=False)
    """ Les settings par défaut pour ce user """
    settings = models.ForeignKey(CollaborativeSettings)

    def change_settings(self, new_settings):
        self.settings = new_settings
        self.save()

    """ https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone """
    """ Signaux: faire en sorte qu'un objet StudentCollaborator existe si on a un modele """
    @receiver(post_save, sender=User)
    def create_student_collaborator_profile(sender, instance, created, **kwargs):
        if created:
            """ On crée effectivement notre profile """
            StudentCollaborator.objects.create(
                user=instance,
                collaborative_tool=False,
                settings=CollaborativeSettings.objects.create()  # Initialisé avec les settings par défaut
            )

Can you help me ? 你能帮助我吗 ?

Thanks 谢谢

It is good if you register ORM object handler. 如果您注册ORM对象处理程序,那就很好。 Add

objects = StudentCollaboratorManager()

to your StudentCollaborator class. 到您的StudentCollaborator类。

Then define: 然后定义:

class StudentCollaboratorManager(BaseUserManager):

    def create_user(self, username, email, password, code_postal, collaborative_tool, **extra_fields):
        baseuser = User.objects.create(username, email, password)
        )
        user = self.model(
            user=baseuser,
            collaborative_tool=collaborative_tool,
            code_postal=code_postal,
            **extra_fields
        )

        #baseuser.set_password(password) #not needed
        baseuser.save(using=self._db)
        user.save(using=self._db)

        return user

If you're looking for a way to create StudentCollaborator for other users which already exist then you can simply do it by a code. 如果您正在寻找一种为已经存在的其他用户创建StudentCollaborator的方法,则只需通过代码即可完成。

Your signal only works when a new user has been added to user model so you have to create StudentCollaborator for other users. 仅当将新用户添加到用户模型时,您的信号才起作用,因此您必须为其他用户创建StudentCollaborator

This is a simple code you can use to create StudentCollaborator for your users: 这是一个简单的代码,可用于为用户创建StudentCollaborator

users = User.objects.all()
for user in users:
    collaborator = StudentCollaborator.objects.filter(user=user)
    if collaborator.count() < 1:
        settings = CollaborativeSettings.objects.create()
        StudentCollaborator.objects.create(user=user, settings=settings)

You need to run this code once to create a StudentCollaborator for your users and after that your signal will to this job for new users. 您需要运行一次此代码才能为您的用户创建一个StudentCollaborator,然后您的信号将向新用户发送此作业。

you could overwrite the save() method for your StudentCollaborator Model, just check if the primary key of the instance exist (self.pk). 您可以覆盖StudentCollaborator模型的save()方法,只需检查实例的主键是否存在(self.pk)。 If it does then get that ModelInstance and update the Instance on .save() 如果确实存在,则获取该ModelInstance并更新.save()上的实例。

def save(self, *args, **kwargs):
    """Overwriting save method to avoid duplicate keys on new account creation."""
    if not self.pk:
        try:
            profile = StudentCollaborator.objects.get(user=self.user)
            self.pk = profile.pk
        except StudentCollaborator.DoesNotExist:
            pass

    super(StudentCollaborator, self).save(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM