【问题标题】:How do I make each individual a user from a model?如何让每个人成为模型中的用户?
【发布时间】:2021-07-15 00:56:51
【问题描述】:

这可能很简单,但对我来说却是一件令人头疼的事情。 我想让 TeacherData 模型中的每个老师都成为使用 first_name 作为用户名和电子邮件作为密码的用户。这是我的模型。

学校模型

class School(models.Model):
    name = models.CharField(max_length=100,null=True,blank=True)

用户模型

class User(AbstractUser):
    school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True)
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)

教师模型

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()

如果还有什么需要告诉我,我会补充的。

【问题讨论】:

    标签: python-3.x django django-models django-views


    【解决方案1】:

    这是在模型级别完成的,如图所示。

    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)
    

    【讨论】:

    • 谢谢。工作得很好。问题是当我尝试编辑时,它抱怨唯一约束失败:accounts_user.username。这就像它试图通过保存编辑的老师来创建另一个用户。我该如何解决????
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多