Django:在forms.py中触发KeyError

时间:2016-10-12 15:14:59

标签: python django

制作卡片应用。用户可以制作一副牌并将牌放入该牌组。卡片和卡片在其模型中有一个“所有者”字段,用于说明用户是谁。

forms.py

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')

触发KeyError的部分是

super(CardForm, self).__init__(*args, **kwargs)

views.py

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})

models.py

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)

1 个答案:

答案 0 :(得分:1)

您应该传递owner作为POST请求,就像您已经为GET请求所做的那样。

if request.method == "POST":
    form = CardForm(request.POST, owner=request.user)