2017-07-30 7 views
-1

教師が個々の生徒のレッスンを登録できるアプリがあります。教師が新しいレッスンを追加すると、このレッスンを教えた先生として自動的に登録されます。フォーム内には、このデータにrequest.userが使用されているため、「教師」のようなフィールドはありません。ユーザーが所属するグループによってユーザーフィールドが表示される

しかし、私は管理者に先生にレッスンを登録してもらいたいと思います。このフォームには「教師」フィールドも必要です。それを行う正しい方法は何ですか? models.py

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

ので、私は右、私は、ユーザーがタイプをadminに属している場合フィールドリストに'Teacher'を追加する必要があると思いますか?

+0

あなたは何をしたいのですか? – hansTheFranz

答えて

1

この場合、Formを自分で作成する必要があります。これにより、ユーザーに基づいてフィールドを上書きすることができます。

あなたはviews.pyでフォームを作成するときは、ユーザーkwargに渡す必要があり

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

forms.py:私は、私は非常にお勧めているストレートdjango-bracesからget_form_kwargs()を取っ

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

- あなたは表示にUserFormKwargsMixinを追加し、フォームにUserKwargModelFormMixinを追加するだけで、ユーザーのすべてのポップをスキップできます。

関連する問題