Answer the question
In order to leave comments, you need to log in
Why doesn't CreateView pass an argument to the form?
I override the form field's queryset by passing an additional argument ( employee_pk ) from the get_form_kwargs method to the form's __init__ method. I try 2 ways, both do not work.
First:
class SkillTestCreateView(AuthorizedMixin, CreateView):
model = Skill
form_class = SkillGroupCreateForm
template_name = 'skill_create.html'
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['employee_pk'] = self.kwargs['pk']
return kwargs
def get_context_data(self, **kwargs):
print(self.kwargs['pk']) ---> выводит нужный id
context = super(SkillTestCreateView, self).get_context_data(**kwargs)
class SkillGroupCreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.employee_pk = kwargs.pop('employee_pk', None) #
super(SkillGroupCreateForm, self).__init__(*args, **kwargs)
self.fields['technology'].required = False
if self.employee_pk:
self.fields['technology'].queryset = Technology.objects.exclude(skill__employee_id=self.employee_pk)
class SkillCreateView(AuthorizedMixin, CreateView):
model = Skill
form_class = SkillCreateForm
template_name = 'employee_info_create.html'
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs.update(employee_pk=self.kwargs['pk'])
return kwargs
class SkillCreateForm(forms.ModelForm):
def __init__(self, *args, employee_pk=None, **kwargs):
super().__init__(*args, **kwargs)
if employee_pk is not None:
self.fields['technology'].queryset = Technology.objects.exclude(
skill__employee_id=employee_pk
)
Answer the question
In order to leave comments, you need to log in
def get_form_kwargs(self):
kwargs = super(SkillTestCreateView, self).get_form_kwargs()
kwargs['employee_pk'] = self.kwargs['pk']
return kwargs
class SkillGroupCreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
employee_pk = kwargs.pop('employee_pk', None) #
super(SkillGroupCreateForm, self).__init__(*args, **kwargs)
self.fields['technology'].required = False
if employee_pk:
# Код дальше
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question