Django FilteredSelectMultiple: '渲染时TypeError:解包非序列
我想在管理后台把默认的 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 个回答
3
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()]