0

我有以下代码

模型.py

fitness_choices = (('wl', 'Weight Loss'), ('ft', 'Firming and Toning'),
                   ('yo', 'Yoga'), ('ot', 'Others'), )
periods_to_train = (('da', 'Daily'), ('ft', 'Few Times A Week'),
                    ('oa', 'Once A Week'), )

class Fitness(models.Model):
    fitness_goals = models.CharField(max_length=80, choices=fitness_choices)
    training_periods = models.CharField(max_length=5, choices=periods_to_train)

表格.py

class FitnessForm(ModelForm):
    fitness_goals = forms.MultipleChoiceField(
            choices=fitness_choices, widget=forms.CheckboxSelectMultiple)
    training_periods = forms.MultipleChoiceField(
            choices=DAYS_OF_WEEK, widget=forms.CheckboxSelectMultiple)

    class Meta:
          model = Fitness

视图.py

from apps.services.forms import FitnessForm

def fitness(request):
    """ Creating a Fitness RFQ """
    fitness_rfq_form = FitnessForm()
    if request.method == 'POST':
        fitness_rfq_form = FitnessForm(request.POST)
        if fitness_rfq_form.is_valid():
            obj = fitness_rfq_form.save(commit=False)
            obj.user = request.user
            obj.save()
            return HttpResponseRedirect(reverse('home'))
    context = {'fitness_rfq_form': fitness_rfq_form}
    return render(request, 'services/fitness_rfq.html', context)

但是当我尝试提交时,我收到如下验证错误

Select a valid choice. [u'wl', u'ft'] is not one of the available choices.

Select a valid choice. [u'0', u'1'] is not one of the available choices.

那么为什么即使我们在 ModelForm 中将它作为 MultiplechoiceField 提到它,它仍然显示上述验证错误?

4

1 回答 1

0

您不应该choices在模型字段中指定...这是验证失败的部分。

您的表单工作正常,多项选择字段的结果当然是所选选项的列表。但是您的模型字段期望来自choices.

如果要将所选选项的列表存储在 CharField 中,则需要先将它们转换为字符串,可能通过json.dumps

于 2014-10-30T09:00:44.000 回答