0

我想了一会儿。我至少有两个演员/角色。“学生”和“导师”。到目前为止,我所做的是做出这样的选择字段:

    class UserProfile(UserenaBaseProfile):

        Roles = [('Student' , 'Student') , ('Tutor' , 'Tutor')]
        ..
        role = models.CharField(max_length = 20 , choices = actor_type , blank = True , null = True)

现在我被困在如何在视图中划分它们!

有一种方法可以user_passes_test在视图上使用,但我也不知道如何制作组?!

如果我只有一个学生,我可以这样做:

class Student(UserProfile):
    """ 
    The Student actor and its necessary fields
    """

    courses        = models.ManyToManyField('courses.Course' , null = True, blank = True, related_name = _('student') , through = 'Registration')

    class Meta:
        verbose_name = _("Student")
        verbose_name_plural = _("Students")

    def save(self , *args , **kwargs):
        super(Student , self).save(*args , **kwargs)

        user, created = User.objects.get_or_create(username=self.username)
        group , created = Group.objects.get_or_create(name = "Student")
        if created: group.save()
        user.groups.add(group)
        user.save()

您能否告诉我有关如何执行此操作的详细答案:

4

1 回答 1

1
@user_passes_test(lambda u: u.groups.filter(name='Student').exists())
def my_student_only_view(request):
    ...

更新

如果您想使用Student自动过滤到“学生”组中的用户并自动将用户保存到该组的实际类,请使用代理模型和 subclass User,而不是UserProfile

class StudentManager(models.Manager):
    def get_query_set(self, *args, **kwargs):
        qs = super(StudentManager, self).get_query_set(*args, **kwargs)
        return qs.filter(groups__name='Student')

class Student(User):
    class Meta:
        proxy = True

    objects = StudentManager()

    def save(self, *args, **kwargs):
        super(Student, self).save(*args, **kwargs)
        group, created = Group.objects.get_or_create(name='Student')
        self.groups.add(group)
于 2012-07-23T16:22:32.957 回答