0

我有一个 django 视图,它将请求中的数据添加到数据库中(我已经使用 ModelForms 完成了)。我有这个 ModelForms 类:

class AddForm(forms.ModelForm):

class Meta:
    model = Product
    fields = ('name', 'price', 'category',)

当我以表格形式输入数据时,我会在视图中传递数据:

    if request.method == 'POST': # If the form has been submitted...
    name_add = request.POST.get("name")
    form = AddForm(request.POST) # A form bound to the POST datas
    not_add = 0
    if form.is_valid(): # All validation rules pass
        for n in Product.objects.filter(dashboard = curr_dashboard):
            if n.name == name_add:
                not_add = 1
        if not_add != 1:
            obj = form.save(commit=False)
            obj.dashboard = curr_dashboard
            obj.save()
            curr_buylist.add_product(obj.id)
            return HttpResponseRedirect(request.get_full_path()) # Redirect after POST
        else:
            forms.ValidationError("You already have this")
            return HttpResponseRedirect(request.get_full_path())

else:
    form = AddForm() # An unbound form

问题是当我尝试测试它时无法测试它,因为我没有请求(我不知道传递一些数据)这是我在测试中所拥有的:

    def test_model_form(self):
    product = Product(name="SomeProduct")
    product_form = AddForm({'name': 'sothingtest', 'price': 100, 'category': 1}, instance= product)
    self.assertEquals(product_form.is_valid(), True)

但它只测试 AddForm 类

4

1 回答 1

0

我不确定这是否是您正在寻找的,但我会这样做:

将验证移到表单中

class AddForm(forms.ModelForm):
    def clean_name(self):
        name = self.cleaned_data.get('name', '').strip()
        if Product.objects.filter(dashboard=curr_dashboard,
                                  name=name).count():
            raise forms.ValidationError(_("name is not unique"))
        return name

    class Meta:
        model = Product
        fields = ('name', 'price', 'category',)

并且在视图中

if request.method == 'POST': # If the form has been submitted...
    form = AddForm(request.POST, instance=Product(dashboard=curr_dashboard) # A form bound to  the POST datas
    if form.is_valid(): # All validation rules pass
        obj = form.save()
        curr_buylist.add_product(obj.id)
        return HttpResponseRedirect(request.get_full_path()) # Redirect after POST
    else:
        return {'form': form} # just return invalid form with validation errors inside

要对此进行测试,请使用 django TestClient(如果您想测试端到端行为)。如果您想编写单元测试,您应该创建自己的请求并填充请求字典。

if如果您想要或为 thyis 编写测试,您可以模拟表单本身并测试逻辑if

于 2013-10-23T15:42:14.487 回答