其他类似的问题并未解决我的问题。
我收到错误消息:
(隐藏字段顺序)内联外键与父实例主键不匹配。
尝试从编辑表单(即已存在的数据)进行保存时。在我看来,我还有另一种保存新数据的方法。
my views.py:
def order_edit(request, order_id):
if request.POST:
form = OrderForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
drink_formset = DrinkFormSet(request.POST, instance=order)
if drink_formset.is_valid():
OrderService.save_order(order, drink_formset)
return HttpResponseRedirect(reverse('coffee:dashboard'))
else:
order = OrderService.load_order(order_id, request)
form = OrderForm(instance=order)
drink_formset = DrinkFormSet(instance=order)
return render(request, 'coffee/order_edit.html', {
'form': form,
'drink_formset': drink_formset,
})
我在forms.py中定义了这个:
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['description_text', ]
class DrinkForm(forms.ModelForm):
class Meta:
model = Drink
fields = ['type_of_drink']
DrinkFormSet = inlineformset_factory(
Order,
Drink,
form=DrinkForm,
can_delete=False,
extra=10)
这是我的models.py:
class Order(models.Model):
description_text = models.CharField(max_length=200)
date = models.DateTimeField('date made')
user = models.ForeignKey(User, null=True, blank=True, )
def __str__(self):
return self.description_text
def was_recent(self):
return self.date >= timezone.now() - datetime.timedelta(days=1)
was_recent.admin_order_field = 'date'
was_recent.boolean = True
was_recent.short_description = 'Recent?'
class Drink(models.Model):
order = models.ForeignKey(Order,)
type_of_drink = models.CharField(max_length=200)
placed = models.BooleanField(default=False)
paid = models.BooleanField(default=False)
def __str__(self):
return self.type_of_drink
感谢任何帮助。我被困在这2个小时以上,感到沮丧:)。