问题
I have view to submit data. From the web browser, i can submit data and redirected nicely. But on the test, i got the error: didn't return an HttpResponse object. It returned None instead.
How can i pass my test?
The view code is:
def insert_barang_po(request, po_id=None):
"submit barang2 dalam PO, ditamilkan setelah insert PO"
po = get_object_or_404(PurchaseOrder, id=po_id)
context = {'menu_sales': True,}
context['po'] = {'id': po.id,}
if request.method == 'POST':
form = InsertBarangPOForm(request.POST)
if form.is_valid():
barang_po = BarangPurchaseOrder.objects.create(
po=form.cleaned_data['po'],
finish_good=form.cleaned_data['finish_good'],
jumlah_barang=form.cleaned_data['jumlah_barang'])
return redirect(reverse('sales:insert_barang_po', args=[po.id]))
else:
form = InsertBarangPOForm(initial={'po':po,})
context['form'] = form
return render(request, 'sales/insert_barang_po.html', context)
The model code is:
class BarangPurchaseOrder(models.Model):
"Menyimpan isi dari setiap PO yg diterima"
po = models.ForeignKey(PurchaseOrder)
finish_good = models.ForeignKey(FinishGood)
jumlah_barang = models.IntegerField()
def __unicode__(self):
return self.finish_good.nama
The test code is
def test_insert_barang_po_valid_po_id(self):
po = PurchaseOrder.objects.create(nomor_po='zaneti')
fg = FinishGood.objects.create(nama='selesai', code='sls')
c = Client()
response = c.post(reverse('sales:insert_barang_po', args=[po.id]),
{'po': po,
'finish_good': fg.id,
'jumlah_barang': '35',},
follow=True)
bpo = BarangPurchaseOrder.objects.filter(finish_good=fg) \
.order_by('id').reverse()
self.assertEqual(bpo[0].jumlah_barang, 35)
回答1:
Your views.py doesn't cover all the cases. If the form is invalid, your method simply returns nothing, that's why you have this error message. You should have an else
statement corresponding to if form.is_valid()
statement.
来源:https://stackoverflow.com/questions/32810931/django-test-valueerror-the-view-didnt-return-an-httpresponse-object-it-return