根据用户所属的组使用户字段可见

时间:2017-07-30 12:24:55

标签: django django-models django-forms

有一个应用程序,教师可以在其中注册他们与个别学生的课程。如果教师添加了新课程,那么他将自动注册为教授本课程的教师。因此,在表单中没有“教师”这样的字段,因为request.user用于此数据。

但我也希望管理员为老师注册课程。然后这个表格也应该有一个“教师”字段。什么是正确的方法?

models.py中的

class Lesson(models.Model):
    pupil = models.ForeignKey(Pupil, on_delete=models.CASCADE)
    teacher = models.ForeignKey("auth.User",
                                limit_choices_to={'groups__name': "teachers"})
views.py中的

class LessonCreate(PermissionRequiredMixin, CreateView, ):
    model = Lesson
    fields = ['pupil', 'subject', ]
    permission_required = 'foreigntest.add_lesson'
    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.teacher = self.request.user
        obj.save()

所以如果用户属于管理员类型,我想我必须在字段列表中添加'Teacher',对吗?

1 个答案:

答案 0 :(得分:1)

您应该为自己创建Form,这样您就可以根据用户覆盖字段。

forms.py

class LessonCreateForm(ModelForm):
    class Meta:
        model = Lesson
        fields = ['pupil', 'subject', 'teacher']

    def __init__(self, *args, **kwargs):
        user = self.kwargs.pop('user', None)
        super(LessonCreateForm, self).__init__(*args, **kwargs)

        # This is the special part - we leave the teacher field in by default
        # When the form is created, we check the user and see if they are an admin
        # If not, remove the field.
        if not user.is_admin:
            self.fields.pop('teacher')

views.py中创建表单时,需要传入用户kwarg:

class LessonCreate(PermissionRequiredMixin, CreateView, ):
    model = Lesson
    fields = ['pupil', 'subject', ]
    permission_required = 'foreigntest.add_lesson'
    form_class = LessonCreateForm

    def get_form_kwargs(self):
        kwargs = super(UserFormKwargsMixin, self).get_form_kwargs()
        # Update the existing form kwargs dict with the request's user.
        kwargs.update({"user": self.request.user})
        return kwargs

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.teacher = self.request.user
        obj.save()

我从django-braces直接get_form_kwargs()我强烈推荐 - 您只需将UserFormKwargsMixin添加到您的视图中,UserKwargModelFormMixin添加到您的表单中,然后跳过所有弹出用户。