Django KeyError kwargs.pop('pk')
<p>I'm using CBV in Django 1.9 and in CreateView when I try to pass an additional parameter ('pk') to my form using self.kwargs.pop('pk') i got "Key Error" but if I get the parameter by index it works, here is my code:</p>

<pre><code>def get_form(self, form_class=None, **kwargs):
    self.project_version_pk = self.kwargs.pop('pk')
    form = super(HRCreateView, self).get_form(form_class)
    form.fields['project_version'].queryset = form.fields['project_version'].queryset.filter(pk=self.project_version_pk)
    form.fields['project_version'].initial = self.project_version_pk
    return form

def get(self, request, *args, **kwargs):
    self.object = None
    form_class = self.get_form_class()
    form = self.get_form(form_class, pk=self.kwargs['pk'])

    return self.render_to_response(
        self.get_context_data(form=form)
</code></pre>

<p>And I get this error:</p>

<p>builtins.KeyError
KeyError: 'pk'</p>

<pre><code>File "RelationView.py", line 65, in get_form

self.project_version_pk = self.kwargs.pop('pk')

KeyError: 'pk'
</code></pre>

<p>But if i read the key this way it works:</p>

<pre><code>def get_form(self, form_class=None, **kwargs):
    self.project_version_pk = self.kwargs['pk']
    form = super(HRCreateView, self).get_form(form_class)
    form.fields['project_version'].queryset = form.fields['project_version'].queryset.filter(pk=self.project_version_pk)
    form.fields['project_version'].initial = self.project_version_pk
    return form
</code></pre>

<p>I don't really understand why the parameter is missing on pop() or which is the best practice for this.</p>

<p>Firstly, you shouldn't be overriding <code>get</code>. In a CreateView, Django already calls <code>get_form</code> for you - inside <code>get_context_data</code>. This is the cause of the issue you are having; you call <code>get_form</code> and pop the pk so that it is no longer in kwargs; but Django calls it again in get_context_data, but this second time it can't find the pk because you removed it the first time.</p>

<p>So don't use pop; but, as I said, don't do this at all. The only thing you actually need to override is <code>get_form</code>.</p>

python django django-class-based-views class-based-views