I'm working on a project in which a teacher can add marks to his students, I want to use formset_factory so the teacher can add many marks at the same time, but I want a teacher to see only his students, and not the students who are not in his class.
I got it when using a single form, but when I try to use the formset_factory, I get this error:
init() got an unexpected keyword argument 'request'
This is my working code in views:
class AddNotaBlock(FormView):
template_name='notas/insertar_nota.html'
form_class= NotaCreateFormTeacher
success_url= reverse_lazy('home')
def get_form_kwargs(self):
""" Passes the request object to the form class.
This is necessary to only display members that belong to a given user"""
kwargs = super(AddNotaBlock, self).get_form_kwargs()
kwargs['request'] = self.request
return kwargs
in forms:
class NotaCreateFormTeacher(ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(NotaCreateFormTeacher, self).__init__(*args, **kwargs)
usuario=self.request.user
profe=Teacher_profile.objects.get(profesor=usuario)
colegio=profe.colegio
self.fields['Username'].queryset = Student_profile.objects.filter(
colegio=colegio)
class Meta:
model = Nota
fields = ('Username', 'nota', 'colegio')
widgets= {'colegio':HiddenInput()}
formset=formset_factory(NotaCreateFormTeacher, extra=2)
when I use:
form_class= NotaCreateFormTeacher
Everything works (but only a form is displayed) If I use:
form_class=formset
I get the unexpected keyword argument error:
init() got an unexpected keyword argument 'request'
What I'm I doing wrong?
Thanks for helping.
CodePudding user response:
You pass this as form_kwargs=…
parameter [Django-doc], so:
class AddNotaBlock(FormView):
template_name = 'notas/insertar_nota.html'
form_class = formset
success_url = reverse_lazy('home')
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs.setdefault('form_kwargs', {})['request'] = self.request
return kwargs