django测试ValueError

django测试ValueError

本文介绍了django测试ValueError:该视图未返回HttpResponse对象。它返回None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有意见要提交数据。从Web浏览器,我可以提交数据并很好地重定向。但是在测试中,我得到了一个错误:没有返回HttpResponse对象。

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.

我如何通过考试?

查看代码为:

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)

模型代码是:

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

测试代码为

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)


推荐答案

您的views.py不能涵盖所有情况。如果表单无效,则您的方法只会返回任何内容,这就是您收到此错误消息的原因。您应该有一个 else 语句,该语句对应于 if form.is_valid()语句。

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.

这篇关于django测试ValueError:该视图未返回HttpResponse对象。它返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 16:37