J
J
Jekson2019-08-02 10:37:01
Django
Jekson, 2019-08-02 10:37:01

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)

forms.py
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)

Second way:
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

forms.py
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
           )

Both times employee_pk=None

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-08-02
@alternativshik

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 question

Ask a Question

731 491 924 answers to any question