Reputation: 26668
I have the following code
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)
But when i am trying to submit i am getting the validation error as below
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.
So why it was showing above validation error even though we have mentioned it as MultiplechoiceField in ModelForm ?
Upvotes: 0
Views: 47
Reputation: 33833
You should not specify choices
in the model field... this is the part that is failing validation.
Your form is working fine and the result of the multiple choice field is, of course, a list of selected choices. But then your model field is expecting a single value from the choices
.
If you want to store the list of selected choices in a CharField you need to convert them to a string first, perhaps via json.dumps
Upvotes: 0