我使用内联formset进行订购系统。用户选择一个项目,然后输入他们想要的项目数量。
formset使用此模型表单。我尝试使用clean方法查看是否有所选项目的库存。我得到的错误是OrderedItemForm'对象没有属性' item'
class OrderedItemForm(forms.ModelForm):
item = forms.ModelChoiceField(queryset=Item.objects.all(), empty_label="(Nothing)")
quantity = forms.IntegerField(min_value=1)
def clean(self):
count = Item.objects.get(pk=self.item.pk)
if(self.quantity > count):
raise ValidationError("Insufficient inventory")
class Meta:
model = OrderedItem
以下是我使用的模型:
class Item(models.Model):
name = models.CharField(max_length=150)
inventory = models.PositiveIntegerField(default=0)
price = models.DecimalField(decimal_places=2, max_digits=5, default=0.0)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
class Order(models.Model):
customer = models.CharField(max_length=150)
setup = models.DateTimeField()
takedown = models.DateTimeField()
address = models.TextField()
created = models.DateField(auto_now_add=True)
def __unicode__(self):
return u"%s's order" % self.customer
class OrderedItem(models.Model):
order = models.ForeignKey(Order, related_name='ordered_items')
item = models.ForeignKey(Item, related_name='orders')
quantity = models.PositiveSmallIntegerField()
def __unicode__(self):
return u"%s (%d)" % (self.item, self.quantity)
观点:
def order_form(request):
OrderedItemFormset = get_ordereditem_formset(OrderedItemForm, extra=1, can_delete=True)
order = Order()
if request.method == 'POST':
form = OrderForm(request.POST, instance=order)
formset = OrderedItemFormset(request.POST, instance=order)
if form.is_valid() and formset.is_valid():
order = form.save()
formset.save()
total = 0.0
data = []
for item in order.ordered_items.all():
data.append({
'order': item.order.id,
'product': str(item.item.name),
'quantity': item.quantity,
'total': (item.item.price*item.quantity)
})
total += float((item.item.price*item.quantity))
return render(request, "order_success.html", {
'ordered_items': data,
'grand_total': total,
'order_num': order.pk,
'order_name': order.customer,
})
else:
form = OrderForm(instance=order)
formset = OrderedItemFormset(instance=order)
return render(request, "order_form.html", {'form': form, 'formset': formset})
答案 0 :(得分:1)
字段数据应从表单的cleaned_data
字典中获取:
def clean(self):
item = self.cleaned_data['item']
quantity = self.cleaned_data['quantity']
if(quantity > item.inventory):
raise ValidationError("Insufficient inventory")