Django单元测试中的POST复选框值

时间:2015-03-05 09:43:08

标签: python django unit-testing

我试图在Django单元测试中测试POST请求,并且此POST请求将被重定向到其他URL,但响应未被重定向,当我打印响应时,我发现有错误消息该复选框是必需的,这也是我的请求未被重定向的原因。

错误:

断言错误:响应没有按预期重定向:响应代码为200(预计为302)

HTML

    <p>
    <label for="id_is_urgent">Is urgent:</label> 
    <input checked="checked" id="id_is_urgent" name="is_urgent" type="checkbox" />
</p>
    <ul class="errorlist">
       <li>This field is required.</li>
    </ul>

test_views.py

 def test_post_order_details_view(self):
        expected_url_for_order_list = reverse('order_update', args=(self.order.id,))
        response = self.client.post(reverse('order_update', args=(self.order.id,)),
                                {'customer': str(self.customer.id),
                                 'service': str(self.service.id),
                                 'order_type': str(self.order_type.id),
                                 'assigned_to': str(self.user.id),
                                 'status': str(self.order_status.id),
                                 'order_status_action': str(self.order_status_action.id),
                                 'is_urgent': True}, follow=True
        self.assertEqual(response.status_code, 200)

view.py

def order_update(request, pk, template_name='orders_app/order_details.html'):
    order = get_object_or_404(CustomerOrder, pk=pk)
    order_lines = OrderLine.objects.filter(order_id=pk)
    customer = order.customer
    service = order.service
    contacts = order.customer.customer_contacts_info.all()

    form = OrderForm(request.POST or None, instance=order)

    if request.method == 'POST':
        if form.is_valid():
            order = form.save()
            messages.info(request, 'Customer Order %s save successfully' % order.id)
            return redirect(reverse('order_update', args=(order.id,)))
    return render(request, template_name, {'form': form,
                                           'order': order,
                                           'lines': order_lines,
                                           'customer': customer,
                                           'service': service,
                                           'contacts': contacts})

forms.py

class OrderForm(ModelForm):
    notes = forms.CharField(widget=forms.Textarea, required=False)
    is_urgent = forms.BooleanField(required=False)


    class Meta:
        model = CustomerOrder
        fields = ['customer', 'service','status', 'order_status_action', 'order_type', 'assigned_to',
                  'notes', 'is_urgent', 'discount_percentage']

1 个答案:

答案 0 :(得分:0)

只需在OrderForm中设置不需要的复选框字段:https://docs.djangoproject.com/en/dev/ref/forms/fields/#required