我有一个 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 类