python - modelformset __iter__ 重载问题

标签 python django django-forms

我正在编写自定义模型表单集。我需要按字段“排序”的值对表单进行排序。我在子表单集类中重载了 BaseFormSet 的 __iter__ 方法。

我的类继承自BaseFormSet:

class SortedCatForms(BaseFormSet):
    def __iter__(self):
        return iter(self.forms.sort(
                            key=lambda form: form['ordering'].value())) #line 38, the problem line.

    def __getitem__(self, index):
        return list(self)[index]

我在我的模型中使用它:

OrderCatsFormSet = modelformset_factory(ParentCategory,
                                    fields=('category', 'ordering'),
                                    formset=SortedCatForms,
                                    extra=0)

问题是:

Caught TypeError while rendering: 'NoneType' object is not iterable

Exception Location: ...forms.py in __iter__, line 38

但是在源BaseFormSet中:

def __iter__(self):
    """Yields the forms in the order they should be rendered"""
    return iter(self.forms)

我的代码有什么问题?如何以正确的方式做到这一点?

编辑:

full traceback

编辑:

在@bobince 的建议下我的代码变成了这样:

class SortedCatForms(BaseFormSet):
def __iter__(self):
    return iter(
            sorted(self.forms, key=lambda form: form['ordering'].value()))

def __getitem__(self, index):
    return list(self)[index]

它返回没有表单的空列表。 __getitem__ 有问题吗?

最佳答案

对 Django 不够熟悉,无法判断这是否是正确的方法,但这里有一个简单的陷阱:

return iter(self.forms.sort( ...

sort() 是列表上的一种方法,可就地对其进行排序并返回 None。你的意思可能是:

return iter(sorted(self.forms, ...

关于python - modelformset __iter__ 重载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7393615/

相关文章:

python - python中Popen的性能开销是多少

python - 从调用模块的位置获取当前路径

python - 如何将子流程的结果放入变量中

python - Django pytest 断言错误 : should return body unicode

python - 具有一对多关系的 Django Form

python - 如何在 python 上生成安全 session_id ?

python - 为 Heroku 应用程序禁用 SSL (django)

python - Django Rest Framework - 如何限制使用 Geolocation 返回的结果?

django - modelformset_factory的empty_form初始值

python - Django - 如何在表单的查询集中使用 modelForm 的关联模型