0

I am in Django 1.11 and my question is quite simple :
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 ).

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

jy95
  • 773
  • 13
  • 36
  • So you want to do changes to your model ? After changing you can execute manage.py makemigration and manager.py migrate which will migrate existing user data to new model – Sandeep Lade Nov 01 '17 at 11:08
  • if you want to create `StudentCollaborator` for already exists users you should create data migrations, [read here](https://docs.djangoproject.com/en/1.11/topics/migrations/#data-migrations) – Brown Bear Nov 01 '17 at 11:09
  • thanks for answer. I didn't know data migrations handles extend User models ... – jy95 Nov 01 '17 at 11:12
  • ... Dammit, No simple StudentCollaborator rows in the database ^^ – jy95 Nov 01 '17 at 11:34

3 Answers3

0

It is good if you register ORM object handler. Add

objects = StudentCollaboratorManager()

to your StudentCollaborator class.

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
majvan
  • 51
  • 6
0

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.

Your signal only works when a new user has been added to user model so you have to create StudentCollaborator for other users.

This is a simple code you can use to create StudentCollaborator for your users:

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.

Navid Zarepak
  • 4,148
  • 1
  • 12
  • 26
  • Thanks. My only question with your answer: where should I run this thing ? Directly in the console ^^? – jy95 Nov 01 '17 at 11:37
  • @jy95 you can run it anywhere you want. I used to make a secure url which only i had access to and run these kind of codes because i had to make many changes and working with console every time takes more time to just write codes in view and execute it in browser. – Navid Zarepak Nov 01 '17 at 11:47
0

you could overwrite the save() method for your StudentCollaborator Model, just check if the primary key of the instance exist (self.pk). If it does then get that ModelInstance and update the Instance on .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)
Wolfgang Leon
  • 695
  • 9
  • 20