samedi 29 avril 2017

Django form checkbox unable to save data

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 pref2(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/pref2.html', {'form': form})

It displays the checkbox but I am unable to save that data to database even when I select a single choice. It displays the error:- `

<ul class="errorlist"><li>Subject<ul class="errorlist"><li>Select a valid choice. [&#39;H&#39;, &#39;M&#39;] is not one of the available choices.</li></ul></li></ul>

All help/suggestions are appreciated, thanks.

`




Aucun commentaire:

Enregistrer un commentaire