从python 3到2的自适应代码,super()。\uu init\uu0()

2024-04-27 04:42:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我将使用pythonbook进行测试驱动开发。但是决定使用Python2而不是python3。在第十二章的结尾表单.py书中的代码就像(Python3):

class ExistingListItemForm(ItemForm):

    def __init__(self, for_list, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.instance.list = for_list


    def validate_unique(self):
        try:
            self.instance.validate_unique()
        except ValidationError as e:
            e.error_dict = {'text': [DUPLICATE_ITEM_ERROR]}
            self._update_errors(e)

我的代码(python2):

^{pr2}$

仍有错误:

TypeError: __init__() takes at least 2 arguments (1 given)

更新: 项目表单:

class ItemForm(forms.ModelForm):

    class Meta:
        model = Item
        fields = ('text',)
        widgets = {
            'text': forms.fields.TextInput(attrs={
            'placeholder': 'Enter a to-do item',
            'class': 'form-control input-lg',
            }),
        }
        error_messages = {
            'text': {'required': EMPTY_LIST_ERROR}
        }

    def save(self, for_list):
        self.instance.list = for_list
        return super(ItemForm, self).save()

更新2:

Traceback (most recent call last):
  File "/home/trytec/Desktop/projects/TDD/superlists/lists/tests/test_views.py", line 150, in test_redirects_after_POST
    self.assertRedirects(response, '/lists/%d/' % (new_list.id, ))
  File "/home/trytec/Desktop/virts/TDD/local/lib/python2.7/site-packages/django/test/testcases.py", line 295, in assertRedirects
    secure=(scheme == 'https'))
  File "/home/trytec/Desktop/virts/TDD/local/lib/python2.7/site-packages/django/test/client.py", line 467, in get
    **extra)
  File "/home/trytec/Desktop/virts/TDD/local/lib/python2.7/site-packages/django/test/client.py", line 285, in get
    return self.generic('GET', path, secure=secure, **r)
  File "/home/trytec/Desktop/virts/TDD/local/lib/python2.7/site-packages/django/test/client.py", line 355, in generic
    return self.request(**r)
  File "/home/trytec/Desktop/virts/TDD/local/lib/python2.7/site-packages/django/test/client.py", line 437, in request
    six.reraise(*exc_info)
  File "/home/trytec/Desktop/virts/TDD/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/trytec/Desktop/projects/TDD/superlists/lists/views.py", line 17, in view_list
    form = ExistingListItemForm()
TypeError: __init__() takes at least 2 arguments (1 given)

Tags: inpytestselfhomeliblocalline