Skip to content Skip to sidebar Skip to footer

How Do I Make Each Individual A User From A Model?

This is probably simple but for me it has proved to be a headache. I'd like to make each teacher from TeacherData model to be a user using the first_name as the username and email

Solution 1:

This is done at the model level as shown.

class TeacherData(models.Model):
    school = models.ForeignKey(School,on_delete=models.CASCADE)
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    email = models.EmailField()

    def save(self, *args, **kwargs):
            self.user = User.objects.create_user(username=self.first_name,password=str(self.email),is_teacher = True,is_student = False,school_id=self.school.id)
            self.user.save()  # mandatory as create_user is not recognized as save operation
            super().save(*args, **kwargs)

Post a Comment for "How Do I Make Each Individual A User From A Model?"