I am trying to display a form (with multiple select checkbox) and save the data in database. But having some problem.
Here is my model:
class Preference(models.Model):
CLASS_CHOICES = [('1', '1'), ('2', '2'), ('3', '3')]
BOARD_CHOICES = [('C', 'CBSE'), ('I', 'ICSE'), ('S', 'State Board')]
SUBJECT_CHOICES = [('H', 'HINDI'), ('M', 'MATH'), ('E', 'ENGLISH')]
class = models.CharField(max_length=2, choices=CLASS_CHOICES, default='1', blank=False)
board = models.CharField(max_length=2, choices=BOARD_CHOICES, default='C', blank=False)
subject = models.CharField(max_length=2, choices=SUBJECT_CHOICES, default='M', blank=False)
My form:
class PreferenceForm(forms.ModelForm):
class Meta:
model = Preference
fields = ['class', 'board', 'subject']
widgets = {
'board': forms.RadioSelect(),
'subject': forms.CheckboxSelectMultiple()
}
My view:
def pref(request):
form = PreferenceForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'website/thanks.html')
else:
print(form.errors)
return render(request, 'website/pref.html', {'form': form})
It displays the form with checkbox but I am unable to save that data to database even when I select a single choice.
Error Displayed:- `
<li>Subject<ul class="errorlist"><li>Select a valid choice. ['H', 'M'] is not one of the available choices.</li></ul></li>
All help/suggestions are appreciated, thanks.