Django: KeyError triggered in forms.py
<p>Making a card app. User can make a deck and put cards in that deck. Decks and cards have an 'owner' field in their models to state who the user is.</p>

<p>forms.py</p>

<pre><code>class CardForm(forms.ModelForm):
  def __init__(self, *args, **kwargs):
    # Pop() removes 'user' from the kwargs dictionary and populates the user variable
    user = kwargs.pop('owner') 
    super(CardForm, self).__init__(*args, **kwargs)
    self.fields['deck'] = forms.ModelChoiceField( # modify choices on 'deck' field
        queryset=Deck.objects.filter(owner=user)
  )

class Meta:
    model = Card 
    fields = ('term', 'definition', 'deck')
</code></pre>

<p>The part triggering the KeyError is</p>

<pre><code>super(CardForm, self).__init__(*args, **kwargs)
</code></pre>

<p>views.py</p>

<pre><code>def card_new(request, deck):
  if request.method == "POST":
      form = CardForm(request.POST)
      if form.is_valid():
          card = form.save(commit=False)
          card.save()
          return redirect('card:detail', deck)
  else:
      form = CardForm(initial={'deck': deck}, owner=request.user) # this initial field sets card's deck as current deck
  return render(request, 'card/card_edit.html', {'form': form})
</code></pre>

<p>models.py</p>

<pre><code>class Card(models.Model):
  owner = models.ForeignKey(User, null=True, default=True, related_name='oc')
  term = models.CharField(max_length=100, default='N/A')
  definition = models.TextField(default='N/A')
  deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
</code></pre>

<p>You should pass <code>owner</code> for POST requests, as you already do for GET requests.</p>

<pre><code>if request.method == "POST":
    form = CardForm(request.POST, owner=request.user)
</code></pre>

python django