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

Django 根据用户所属的组使用户字段可见,django,django-models,django-forms,Django,Django Models,Django Forms,有一个应用程序,教师可以注册课程,他们与个别学生。如果教师添加新课程,则他将自动注册为教授此课程的教师。因此,在表单中不存在“Teacher”这样的字段,因为request.user用于此数据 但我也希望管理员为老师注册一节课。那么这个表单也应该有一个“教师”字段。正确的方法是什么 在models.py中: class Lesson(models.Model): pupil = models.ForeignKey(Pupil, on_delete=models.CASCADE)

有一个应用程序,教师可以注册课程,他们与个别学生。如果教师添加新课程,则他将自动注册为教授此课程的教师。因此,在表单中不存在“Teacher”这样的字段,因为
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"})
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()
视图.py中

class Lesson(models.Model):
    pupil = models.ForeignKey(Pupil, on_delete=models.CASCADE)
    teacher = models.ForeignKey("auth.User",
                                limit_choices_to={'groups__name': "teachers"})
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'
添加到字段列表中,对吗?

您应该自己为这个表单创建
表单,这将允许您根据用户覆盖字段

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

我直接使用了
get\u form\u kwargs()
,我强烈建议您只需将
UserFormKwargsMixin
添加到视图中,并将
userkwargmodelmixin
添加到表单中,您就可以跳过用户的所有弹出操作。

那么您实现了您想要做的事情了吗?