modelformset __iter__ overloading problem

痞子三分冷 提交于 2019-12-23 12:42:15

问题


I'm writing the custom modelformset. I need that forms to be sorted by value of field "ordering". I overloaded __iter__ method of BaseFormSet in my child formset class.

My class inherited from 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]

I use it in my modelformset:

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

The problem is:

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

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

But in source BaseFormSet:

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

What is wrong in my code? How to do it in right way?

Edit:

full traceback

Edit:

After @bobince's advice my code became this:

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]

It's returns empty list without forms. Are problem in __getitem__?


回答1:


Not familiar enough with Django to judge whether this is the right way, but here's a simple gotcha:

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

sort() is a method on a list that sorts it in-place and returns None. You probably meant:

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


来源:https://stackoverflow.com/questions/7393615/modelformset-iter-overloading-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!