本文介绍了Django formset单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用formset运行单元测试。



我尝试做一个测试:

  class NewClientTestCase(TestCase):

def setUp(self):
self.c = Client()

def test_0_create_individual_with_same_adress (self):

post_data = {
'ctype':User.CONTACT_INDIVIDUAL,
'username':'dupond.f',
'email':' [email protected]',
'password':'pwd',
'password2':'pwd',
'civility':User.CIVILITY_MISTER,
'first_name' :'François',
'last_name':'DUPOND',
'phone':'+33 1 34 12 52 30',
'gsm':'+33 6 34 12 52 30',
'fax':'+33 1 34 12 52 30',
'form-0-address1':'33 avenue Gambetta',
'form-0-address2' :'apt 50',
'form-0-zip_code':'75020',
'form-0-city':'Paris',
'form-0-country':'FRA' ,
'same_for_billing':True,
}

response = self.c.post(reverse('client:full_account'),post_data,follow = True)

self.assertRedirects(response,'%s?created = 1'%reverse('client:dashboard'))

我有这个错误:

我的观点:

  def full_account(request,url_redirect =''):
从表单导入NewUserFullForm,AddressForm,BaseArticleFormSet

fields_required = []
fields_notrequired = []

AddressFormSet = formset_factory(AddressForm,extra = 2,formset = BaseArticleForm设置)

如果request.method =='POST':
form = NewUserFullForm(request.POST)
objforms = AddressFormSet(request.POST)

如果objforms.is_valid()和form.is_valid():
user = form.save()
address = objforms.forms [0] .save()


如果url_redirect =='':
url_redirect ='%s?created = 1'%reverse('client:dashboard')
logon(request,form.instance)
返回HttpResponseRedirect(url_redirect)
else:
form = NewUserFullForm()
objforms = AddressFormSet()

return direct_to_template(request,'clients / full_account.html' {
'form':form,
'formset':objforms,
'tld_fr':False,
})
pre>

和我的表单文件:

  class BaseArticleFormSet(BaseFormSet):

def clean(self):

msg_err = _('Ce Champ est obligatoire。')
non_errors = True

如果self.data和self.data中的same_for_billing['same_for_billing'] =='on':
same_for_billing = True
else:
same_for_billing = False

在[0,1]中的$:

form = self.forms [i]

for form.fields中的字段:
name_field ='form-%d-%s'%(i,field)
value_field = self.data [name_field] .strip()

如果i == 0和self。 form [0] .fields [field] .required and value_field =='':
form.errors [field] = msg_err
non_errors = False

elif i == 1和不一样_for_billing和self.forms [1] .fields [field] .required和value_field =='':
form.errors [field] = msg_err
non_errors = False

返回non_errors

class AddressForm(forms.ModelForm):

class Meta:
model = Address

address1 = forms.CharField )
address2 = forms.CharField(required = False)
zip_code = forms.CharField()
city = forms.CharField()
country = forms.ChoiceField(choices = CountryField .COUNTRIES,initial ='FRA')


解决方案

每个Django formset包含一个管理表单,需要被包含在该帖子中。 很好地解释了这一点。要在单元测试中使用它,您需要自己写出来。 (我提供的链接显示了一个例子),或者调用 formset.management_form 输出数据。


I can't running Unit Test with formset.

I try to do a test:

class NewClientTestCase(TestCase):

    def setUp(self):
        self.c = Client()

    def test_0_create_individual_with_same_adress(self):

        post_data =  {
            'ctype': User.CONTACT_INDIVIDUAL,
            'username': 'dupond.f',        
            'email': '[email protected]', 
            'password': 'pwd', 
            'password2': 'pwd', 
            'civility': User.CIVILITY_MISTER, 
            'first_name': 'François', 
            'last_name': 'DUPOND', 
            'phone': '+33 1 34 12 52 30', 
            'gsm': '+33 6 34 12 52 30', 
            'fax': '+33 1 34 12 52 30', 
            'form-0-address1': '33 avenue Gambetta', 
            'form-0-address2': 'apt 50', 
            'form-0-zip_code': '75020', 
            'form-0-city': 'Paris', 
            'form-0-country': 'FRA', 
            'same_for_billing': True,            
        }

        response = self.c.post(reverse('client:full_account'), post_data, follow=True)   

        self.assertRedirects(response, '%s?created=1' % reverse('client:dashboard'))

and i have this error:

My view :

def full_account(request, url_redirect=''):    
    from forms import NewUserFullForm,  AddressForm,  BaseArticleFormSet

    fields_required = []
    fields_notrequired = []

    AddressFormSet = formset_factory(AddressForm, extra=2,  formset=BaseArticleFormSet)

    if request.method == 'POST':        
        form = NewUserFullForm(request.POST)        
        objforms = AddressFormSet(request.POST)            

        if objforms.is_valid() and form.is_valid():            
            user = form.save()            
            address = objforms.forms[0].save()


            if url_redirect=='':
                url_redirect = '%s?created=1' % reverse('client:dashboard')
                logon(request, form.instance)            
            return HttpResponseRedirect(url_redirect)
    else:
        form = NewUserFullForm()
        objforms = AddressFormSet()   

    return direct_to_template(request, 'clients/full_account.html', {
        'form':form,
        'formset': objforms, 
        'tld_fr':False, 
    })

and my form file :

class BaseArticleFormSet(BaseFormSet):

    def clean(self):        

        msg_err = _('Ce champ est obligatoire.')
        non_errors = True

        if 'same_for_billing' in self.data and self.data['same_for_billing'] == 'on':
            same_for_billing = True
        else:            
            same_for_billing = False

        for i in [0, 1]:

            form = self.forms[i]           

            for field in form.fields:                                
                name_field = 'form-%d-%s' % (i, field )
                value_field = self.data[name_field].strip()                

                if i == 0 and self.forms[0].fields[field].required and value_field =='':                    
                    form.errors[field] = msg_err                    
                    non_errors = False

                elif i == 1 and not same_for_billing and self.forms[1].fields[field].required and value_field =='':
                    form.errors[field] = msg_err                    
                    non_errors = False

        return non_errors

class AddressForm(forms.ModelForm):

    class Meta:
        model = Address

    address1 = forms.CharField()
    address2 = forms.CharField(required=False)
    zip_code = forms.CharField()
    city = forms.CharField()
    country = forms.ChoiceField(choices=CountryField.COUNTRIES,  initial='FRA')
解决方案

Every Django formset comes with a management form that needs to be included in the post. The official docs explain it pretty well. To use it within your unit test, you either need to write it out yourself. (The link I provided shows an example), or call formset.management_form which outputs the data.

这篇关于Django formset单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 19:09