单元测试django内联formset

时间:2012-03-01 16:35:31

标签: django django-forms inline-formset

在尝试以编程方式通过内联formset发布新的ForeignKey对象时,我收到错误:ValueError: invalid literal for int() with base 10: ''

这是我的测试代码(为了简洁而臃肿):

def test_merits_can_be_added(self):
    self.c = Client()
    self.c.login(username=self.user.username, password='dummy')
    self.post_data = {
      'name':u'Unhappy SE',
      'concept':u'Sad clown',
      'merit-TOTAL_FORMS':u'1',
      'merit-MAX_NUM_FORMS':u'',
      'merit-INITIAL_FORMS':u'1',
      'merit-0-id':u'',
      'merit-0-level':u'2',
      'merit-0-character':u'1',
      'merit-0-trait':u'11',
      'merit-0-specializations':u'Sometimes'
    }
    sheet = GeistCharacterSheet.objects.create(name='Happy SE', user=self.user)
    response = self.c.post(sheet.get_absolute_url(), self.post_data, follow=True)
    self.assertEqual(GeistCharacterSheet.objects.get(pk=1).chosentrait_set.all().filter(trait__name='Common Sense')[0].level, 2)
    self.assertEqual(GeistCharacterSheet.objects.get(pk=1).chosentrait_set.all().filter(trait__name='Common Sense')[0].specializations, u'Sometimes')

视图代码(为简洁而再次修剪):

def character_sheet(request, sheet_id=None):
  charsheet = GeistCharacterSheet.objects.get(pk=sheet_id, user=request.user)
  if request.method == 'POST':
    sheet_form = GeistCharacterSheetForm(request.POST, instance=charsheet)          
    merit_formset = setup_merit_form(charsheet, post=request.POST)

    if sheet_form.is_valid() and merit_formset.is_valid():
      sheet_form.save()
      merit_formset.save()
      return redirect('/character-manager/list/')

def setup_merit_form(charsheet, post=None):
  MeritFormSet = inlineformset_factory(GeistCharacterSheet, ChosenTrait, form=ChosenMeritForm, extra=1)
  if post:
    return MeritFormSet(post, instance=charsheet, queryset=ChosenTrait.objects.filter(trait__trait_type__name='Merit'), prefix='merit')
  else:
    return MeritFormSet(instance=charsheet, queryset=ChosenTrait.objects.filter(trait__trait_type__name='Merit'), prefix='merit')

以下是测试执行的追溯:

Traceback (most recent call last):
  File "C:\charon_sheet\..\charon_sheet\character_manager\tests.py", line 119, in test_skills_can_be_changed
    response = self.c.post(sheet.get_absolute_url(), self.post_data, follow=True)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\test\client.py", line 449, in post
    response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\test\client.py", line 259, in post
    return self.request(**r)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\core\handlers\base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "C:\charon_sheet\..\charon_sheet\character_manager\views.py", line 29, in character_sheet
    merit_formset = setup_merit_form(charsheet, post=request.POST)
  File "C:\charon_sheet\..\charon_sheet\character_manager\views.py", line 69, in setup_merit_form
    return MeritFormSet(post, instance=charsheet, queryset=ChosenTrait.objects.filter(trait__trait_type__name='Merit'), prefix='merit')
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\forms\models.py", line 682, in __init__
    queryset=qs)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\forms\models.py", line 415, in __init__
    super(BaseModelFormSet, self).__init__(**defaults)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\forms\formsets.py", line 47, in __init__
    self._construct_forms()
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\forms\formsets.py", line 108, in _construct_forms
    self.forms.append(self._construct_form(i))
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\forms\models.py", line 691, in _construct_form
    form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\forms\models.py", line 437, in _construct_form
    connection=connections[self.get_queryset().db])
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\db\models\fields\subclassing.py", line 53, in inner
    return func(*args, **kwargs)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\db\models\fields\subclassing.py", line 53, in inner
    return func(*args, **kwargs)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\db\models\fields\__init__.py", line 306, in get_db_prep_lookup
    value = self.get_prep_lookup(lookup_type, value)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\db\models\fields\__init__.py", line 292, in get_prep_lookup
    return self.get_prep_value(value)
  File "C:\Program Files\BitNami DjangoStack\apps\django\django\db\models\fields\__init__.py", line 479, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''

我可以发布模型,表单,更多视图,无论任何人认为有用。

问题在于'merit-0-id':u''帖子项目。我尝试使用和不使用unicode,使用False,使用'new'使用0或-1,使用{{1}}(一个完整的野生镜头,我知道)。

我的主要困惑在于,当我运行服务器时,表单可以正常工作。我在提交表单时检查了POST变量,并且id字段可以为空,并且项目添加得很好。

为什么表格在通过测试跑步者提交时会被阻止?

2 个答案:

答案 0 :(得分:8)

内联formset中的初始表单需要绑定到DB中的现有模型。您的设置不会创建相关的ChosenTrait实例(这是您应该用于merit-0-id的pk)。如果您正在测试创建所有新模型,那么'merit-INITIAL_FORMS'应为0

答案 1 :(得分:0)

空字段与空字符串不相同。

如果某个字段为空,则浏览器根本不会将其包含在查询字符串中。但是,您已使用包含空字符串的字段模拟POST,这会使事情混乱。完全从字典中删除该密钥。