我正在尝试替换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它可以很好地显示,但选择框为空白,我需要在其中包含一些内容。

最佳答案

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


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

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

尝试:

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

10-04 21:26