gpt4 book ai didi

python - Django:在 forms.py 中触发 KeyError

转载 作者:太空宇宙 更新时间:2023-11-03 16:04:18 29 4
gpt4 key购买 nike

制作卡片应用程序。用户可以制作一副牌并将卡片放入该牌堆中。牌组和卡牌的模型中有一个“所有者”字段来说明用户是谁。

表单.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)

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

模型.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)

最佳答案

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

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

关于python - Django:在 forms.py 中触发 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40002239/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com