2014-10-30 56 views
0

我有以下代碼Django的MultpleSelectionField使用情況和錯誤

models.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) 

forms.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 

views.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上述驗證錯誤?

回答

0

您不應在模型字段中指定choices ...這是未通過驗證的部分。

您的表單工作正常,多選字段的結果當然是選定選項的列表。但是你的模型領域預計從choices單個值。

如果要將所選選項的列表存儲在CharField中,則需要先將它們轉換爲字符串,也許可以通過json.dumps

相關問題