我正在思考这一段时间。我至少有两个演员/角色。 “学生”和“导师”。 我到目前为止所做的是做一个像这样的选择领域:
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()
请您详细说明如何执行此操作:
答案 0 :(得分:1)
@user_passes_test(lambda u: u.groups.filter(name='Student').exists())
def my_student_only_view(request):
...
<强>更新强>
如果您希望使用实际Student
类自动过滤到“学生”组中的用户并自动将用户保存到该组,请使用代理模型和子类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)