python - Django 抛出 ValueError : too many values to unpack (expected 2) with no change to the code

标签 python django django-models django-forms

我在子文件夹中编写了一个新函数,运行良好的 django 项目现在抛出以下错误:

 File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\urls.py", line 4, in <module>
    from .views import (
  File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\views.py", line 15, in <module>
    from .forms import IndicatorForm, SearchForIndicatorMetaData
  File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\forms.py", line 24, in <module>
    class IndicatorForm(forms.ModelForm):
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\forms\models.py", line 252, in __new__
    opts.field_classes)
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\forms\models.py", line 166, in fields_for_model
    formfield = f.formfield(**kwargs)
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 1873, in formfield
    return super(IntegerField, self).formfield(**defaults)
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 872, in formfield
    defaults['choices'] = self.get_choices(include_blank=include_blank)
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 802, in get_choices
    for choice, __ in choices:
ValueError: too many values to unpack (expected 2)

过去也曾提出过类似的问题,而且一直有人使用字典而不是可迭代来定义选择。我没有这样做,但我遇到了同样的错误。回溯似乎认为问题出在我的 forms.py 中的某个地方。我的 forms.py 如下:

from django import forms
from .models import Indicator


def get_indicator_ids():
    ids = []
    indicator_objects = Indicator.objects.all()
    for indicator in indicator_objects:
        ids.append(indicator.id)
    return ids


class IndicatorDropDown(forms.Form):
    def __init__(self, *args, **kwargs):
        super(IndicatorDropDown, self).__init__(*args, **kwargs)
        self.fields['indicators'] = forms.ChoiceField(choices=get_indicator_ids())


class IndicatorForm(forms.ModelForm):

    class Meta:
        model = Indicator
        fields = '__all__'
        exclude = ['creator']


class SearchForIndicatorMetaData(forms.Form):
    search_for_indicator_metadata = forms.IntegerField(label='Search for metadata by ID', max_value=999999999)

forms.py 调用模型 Indicator,但这自上次提交以来并没有改变。我所有选择的字段都是元组,因此不应抛出此错误。任何意见,将不胜感激。

编辑 - 添加模型

class Indicator(models.Model):
    time_periods = (
        get_time_periods()
    )

    months = (
        get_months()
    )

    calculations = (
        get_calculations()
    )

    sex_ids = (
        get_all_sexes()
    )

    age_ids = (
        get_all_ages()
    )

    operands = (
       ('+', '+'),
       ('-', '-'),
       ('*', '*'),
       ('/', '/')
    )

    salt_options = get_salt_options_as_tuple()

    qof_data_choices = (
        ('qof-{}-prev-ach-exc-ms-prac.xlsx', 'Musculoskeletal group'),
        ('qof-{}-prev-ach-exc-neu-prac.xlsx', 'Mental health and neurology group'),
        ('qof-{}-prev-ach-exc-fer-obs-gyn-prac.xlsx', 'Fertility, obstetrics and gynaecology group'),
        ('qof-{}-prev-ach-exc-hd-prac.xlsx', 'High dependency and other long term conditions group'),
        ('qof-{}-prev-ach-exc-ls-prac.xlsx', 'Lifestyle group'),
        ('qof-{}-prev-ach-exc-resp-prac.xlsx', 'Respiratory group'),
        ('qof-{}-prev-ach-exc-cv-prac.xlsx', 'Cardiovascular group'),
        ('qof-{}-prac-dom-ach.xlsx', 'Achievement group'),
        ('qof-{}-prac-dom-exc.xlsx', 'Exclusion group'),
    )

    id = models.IntegerField(unique=True, primary_key=True)
    source_data_family = models.ForeignKey(IndicatorFamily, on_delete=models.CASCADE, blank=True)
    qof_source_data = models.CharField(max_length=100, choices=qof_data_choices, blank=True)
    source_sheet = models.CharField(max_length=200, blank=True)
    year_range = models.CharField(max_length=2, blank=True)
    time_period = models.CharField(max_length=30, choices=time_periods, blank=True)
    ageId = models.IntegerField(choices=age_ids, blank=True)
    sexId = models.IntegerField(choices=sex_ids)
    calculation = models.CharField(max_length=30, choices=calculations, blank=True)
    rate = models.IntegerField(blank=True, null=True)
    value_declared_independently = models.BooleanField(default=False)
    value_column_name = models.CharField(max_length=200, blank=True)
    numerator_starts_with_financial_year = models.BooleanField(default=False)
    numerator = models.CharField(max_length=200, blank=True)
    salt_numerator = models.CharField(max_length=200, blank=True, choices=salt_options)
    salt_numerator_operand = models.CharField(max_length=2, choices=operands, blank=True)
    salt_numerator_2 = models.CharField(max_length=200, blank=True, choices=salt_options)
    numerator_minus_not_caseness = models.BooleanField(default=False)
    iapt_q_m_variable_type = models.CharField(max_length=200, blank=True)
    iapt_q_m_variable_a = models.CharField(max_length=200, blank=True)
    iapt_q_m_variable_b = models.CharField(max_length=200, blank=True)
    iapt_q_m_variable_type_denominator = models.CharField(max_length=200, blank=True)
    iapt_q_m_variable_a_denominator = models.CharField(max_length=200, blank=True)
    iapt_q_m_variable_b_denominator = models.CharField(max_length=200, blank=True)
    denominator_starts_with_financial_year = models.BooleanField(default=False)
    denominator = models.CharField(max_length=200, blank=True)
    denominator_minus_not_caseness = models.BooleanField(default=False)
    denominator_source_sheet = models.CharField(max_length=200, blank=True)
    salt_denominator = models.CharField(max_length=200, blank=True, choices=salt_options)
    salt_denominator_operand = models.CharField(max_length=2, choices=operands, blank=True)
    salt_denominator_2 = models.CharField(max_length=200, blank=True, choices=salt_options)
    add_denominator_column = models.CharField(max_length=200, blank=True)
    additional_denominator_column_starts_with_financial_year = models.BooleanField(default=False)
    adjust_denominator_for_person_years = models.BooleanField(default=False)
    ccg_over_18_population_as_denominator = models.BooleanField(default=False)
    ccg_total_population_as_denominator = models.BooleanField(default=False)
    is_count = models.BooleanField(default=False)
    is_percentage = models.BooleanField(default=False)
    ccg_to_stp = models.BooleanField(default=False)
    gp_to_upper_tier_la = models.BooleanField(default=False)
    ccg_lookup_required = models.BooleanField(default=False)
    drop_depression = models.BooleanField(default=False)
    count_non_nulls = models.BooleanField(default=False)
    non_null_columns = models.CharField(max_length=300, blank=True)
    drop_eng_row = models.BooleanField(default=False)
    months_to_quarter = models.BooleanField(default=False)
    snapshot = models.BooleanField(default=False)
    asterisk_as_two = models.BooleanField(default=False)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    denominator_2_equals_denominator = models.BooleanField(default=False)
    do_not_suppress_small_numbers = models.BooleanField(default=False)
    numerator_is_num_minus_denom = models.BooleanField(default=False)
    stp_is_average_not_sum = models.BooleanField(default=False)
    mental_health_trust_geographies = models.BooleanField(default=False)
    filter_by = models.CharField(max_length=200, blank=True)
#    ld_denominator_source_file = models.CharField(max_length=100, choices=qof_data_choices, blank=True)

    def __str__(self):
        return str(self.id)

编辑 2 - 更新回溯:

  File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\urls.py", line 4, in <module>
    from .views import (
  File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\views.py", line 15, in <module>
    from .forms import IndicatorForm, SearchForIndicatorMetaData
  File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\forms.py", line 19, in <module>
    class IndicatorForm(forms.ModelForm):
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\forms\models.py", line 252, in __new__
    opts.field_classes)
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\forms\models.py", line 166, in fields_for_model
    formfield = f.formfield(**kwargs)
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 1873, in formfield
    return super(IntegerField, self).formfield(**defaults)
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 872, in formfield
    defaults['choices'] = self.get_choices(include_blank=include_blank)
  File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 802, in get_choices
    for choice, __ in choices:
ValueError: too many values to unpack (expected 2)

编辑 3 - 添加了从模型调用函数的示例

def get_months():
    months = (
        ('jan', 'January'),
        ('feb', 'February'),
        ('mar', 'March'),
        ('apr', 'April'),
        ('may', 'May'),
        ('jun', 'June'),
        ('jul', 'July'),
        ('aug', 'August'),
        ('sep', 'September'),
        ('oct', 'October'),
        ('nov', 'November'),
        ('dec', 'December')
    )
    return months


def get_time_periods():
    time_periods = (
        ('monthly', 'Monthly'),
        ('quarterly', 'Quarterly'),
        ('annual', 'Annual')
    )
    return time_periods


def get_calculations():
    calcs = (
        ('WILSON', 'Wilson'),
        ('BYAR', 'Byar')
    )
    return calcs

最佳答案

All of my choice fields are tuples, and so should not throw this error.

它会引发错误,因为您在此处添加了一个字段到表单中:

... = forms.ChoiceField(choices=<b>get_indicator_ids()</b>)

并且 get_indicator_ids() 确实返回二元组列表。它只是一个简单的整数列表。

您可以更改 get_indicator_ids 的实现,但事实上,如果我理解正确的话,您希望能够选择 Indicator 对象。那么用ModelChoiceField [Django-doc]就很苦了,例如:

class IndicatorDropDown(forms.Form):

    indicators = forms.<b>Model</b>ChoiceField(<b>queryset=Indicator.objects.all()</b>)

关于python - Django 抛出 ValueError : too many values to unpack (expected 2) with no change to the code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56795366/

相关文章:

python,哈希函数选择

python - 在 VS Code 中选择 python 解释器时出现错误 : spawn ENOTDIR,

javascript - 来自用户麦克风的 WAV 文件与来自文件 : Some difference is causing bugs, 的 WAV 文件,但它们有何不同?

python - Django modelformset order_by 不起作用

python - 使用请求上传文件并发送额外数据

Python:用装饰器计算递归函数的执行时间

python - 新的 Django 应用程序中没有 admin.py 文件

python - 如何通过 id 连接两个模型(没有外键)并按管理中的链接模型字段排序

python - urllib2 是否支持线程到需要基本身份验证的服务器?

多个网站的 Django-cms