Django FilteredSelectMultiple:渲染时出现'TypeError:unpack non-sequence'

时间:2011-02-21 15:23:59

标签: python django

我正在尝试将Admin中的默认ManyToManyField小部件替换为使用FilteredSelectMultiple,我遇到了一些问题。我的错误是Caught TypeError while rendering: unpack non-sequence

这是我的模特

class Car(models.Model):
    parts = models.ManyToManyField('Part')

class Part(models.Model):
    name = models.CharField(max_length=64)

这是我的ModelAdmin

class CarAdmin(admin.ModelAdmin):
    form = myforms.CustomCarForm

这是CustomCarForm

 class CustomCarForm(forms.ModelForm):
     def __init__(self, *args, **kwargs):
         super(CustomCarForm, self).__init__(*args, **kwargs)
         parts = tuple(Part.objects.all())
         self.fields['parts'].widget = admin.widgets.FilteredSelectMultiple(
             'Parts', False, choices=parts
         )

当我尝试查看管理员表单

时收到此错误
Request Method:     GET
Request URL:        http://127.0.0.1:8000/admin/foo/car/1/
Django Version:     1.2.5
Exception Type:     TemplateSyntaxError
Exception Value:    Caught TypeError while rendering: unpack non-sequence
Exception Location: /usr/lib/python2.4/site-packages/Django-1.2.5-py2.4.egg/django/forms/widgets.py in render_options, line 464
Python Executable:  /usr/bin/python
Python Version:     2.4.3

如果我使用其中任何一个设置parts

,就会发生此错误
parts = Part.objects.all()
parts = list(Part.objects.all())
parts = tuple(Part.objects.all())

如果我这样做

parts = Part.objects.value_list('name')

我得到Caught ValueError while rendering: need more than 1 value to unpack

修改:如果我取出choices=parts它渲染得很好,但选择框是空白的,我需要在其中加入一些内容。

1 个答案:

答案 0 :(得分:3)

        for option_value, option_label in chain(self.choices, choices):

显然,选项是元组列表,第一个值为option_value,第二个值为option_label

我不确定第一个需要什么,但我猜pk。

尝试:

parts = [(x.pk, x.name) for x in Part.objects.all()]