MultipleObjectsReturned- get()返回了多个mPurchase-返回了2

时间:2018-11-22 18:09:14

标签: django python-3.x django-models django-forms django-views

我是django的初学者。尝试保存mPurchase表单时,出现“ MultipleObjectReturned”错误。我正在尝试使用POST请求从表单获取数据。每次提交表单时,我都会报错。​​

views.py

def milkPurchase(request):
title='Buy Milk'
milk = mPurchase.objects.all()

if request.method=='POST':
    form=mPurchaseForm(request.POST)
    if form.is_valid():
        m = get_object_or_404(mPurchase)
        m.mPurchase_date=timezone.now()
        m.save()
        return redirect('milk-purchase')

else:
    form=mPurchaseForm()


context = {
    'title': title,
    'form': form,
    'milk':milk

}
return render(request,'dairyapp/milk-purchase.html',context)

forms.py

class mPurchaseForm(forms.ModelForm):
"""
    This form is for milk purchase
"""

seller=forms.CharField(
   label='Seller Name',
    max_length=50,
)

mPurchase_product=forms.ChoiceField(
    choices=MILK_CHOICES,
    label='Milk Type',
    initial='',
    widget=forms.Select(),
    required=True
)

mPurchase_qty=forms.FloatField(
    label='Qty'
)

mPurchase_rate=forms.FloatField(
    label='Rate'
)

class Meta:
    model=mPurchase
    fields=('seller','mPurchase_product','mPurchase_qty','mPurchase_rate',)

这是我的 models.py

class mPurchase(models.Model):
mPurchase_id=models.AutoField(primary_key=True)
seller=models.CharField(max_length=50)
mPurchase_date=models.DateTimeField(default=timezone.now)
mPurchase_product=models.CharField(max_length=10,choices=MILK_CHOICES)
mPurchase_qty=models.FloatField()
mPurchase_rate=models.FloatField()

def __str__(self):
    return self.seller

您能帮我解决这个问题吗?我尝试使用

mPurchase.objects.filter()

还尝试使用ObjectDoesNotExist和MultipleObjectReturned捕获异常

from django.core.exceptions import ObjectDoesNotExist, 
MultipleObjectsReturned

1 个答案:

答案 0 :(得分:0)

您需要在此处更改:

if request.method=='POST':
    form=mPurchaseForm(request.POST)
    if form.is_valid():
        m = form.save(commit=False)  # <--- Here
        m.mPurchase_date=timezone.now()
        m.save()