0

I have CustomUserModel in Django and four roles - user, student, curator, admin And I have group field in CustomUserModel, which default value is Null

Now every User can have group, but I want only students to have it. How can I do this on my model level? (like how to check that you need to have Student role to change the value of the group field from Null to other)

I tried to use validator, but there I can get only the value of group, and can't use self to check like if self.role = STUDENT

USER = 'user'
STUDENT = 'student'
CURATOR = 'curator'
ADMIN = 'admin'

ROLES = (
        (USER, USER),
        (STUDENT, STUDENT),
        (CURATOR, CURATOR),
        (ADMIN, ADMIN),
)

def validate_user_can_have_group(value):
    ###

class User(AbstractUser):
    role = models.CharField(max_length=max([len(role[0]) for role in ROLES]),
                            choices=ROLES,
                            default=USER,)

    group = models.ForeignKey('structure.Group',
                              on_delete=models.SET_NULL,
                              validators=[validate_user_can_have_group],
                              related_name='users',
                              blank=True,
                              null=True,)

    class Meta:
        swappable = "AUTH_USER_MODEL"
        ordering = ['username']

    @property
    def is_admin(self):
        return (
            self.role == ADMIN or self.is_staff
            or self.is_superuser
        )

    @property
    def is_curator(self):
        return self.role == CURATOR

    @property
    def is_student(self):
        return self.role == STUDENT

    @property
    def is_user(self):
        return self.role == USER

    def __str__(self):
        return self.username

VLAD
  • 1
  • 1
  • Does this answer your question? [Django Model validation based on a field value of another Model](https://stackoverflow.com/questions/60636043/django-model-validation-based-on-a-field-value-of-another-model) – Đào Minh Hạt Nov 23 '22 at 04:34

0 Answers0