no_Or no_Or - 6 months ago 15
Python Question

Unable to save the data from checkboxes and radiobuttons using modelForm

model.py

class FormData(models.Model):
email = models.EmailField()
full_name = models.CharField(max_length=120)
text_area = models.CharField(max_length=250)
radio_buttons = models.CharField(max_length=25)
check_boxes = models.CharField(max_length=10)
def __unicode__(self):
return self.email


forms.py

class MyModelForm(forms.ModelForm):
class Meta:
model = FormData
fields = ['text_area','email','full_name']
widgets = {
'text_area': Textarea(attrs={'cols': 50, 'rows': 10}),
}
TYPE_CHOICES = [('s', 'small'),('m', 'medium'),('b', 'big')]
check_boxes = forms.MultipleChoiceField(choices=TYPE_CHOICES, widget=forms.CheckboxSelectMultiple())

CHOICES = [(1, 'One'),(2, 'Two'),(3, 'Three'),(4, 'Four')]
radio_buttons = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())


views.py

def home(request):
title = 'Welcome'
form = MyModelForm(request.POST)
context = {"title":title,"form":form}

if form.is_valid():
instance = form.save(commit=False)
instance.save()
context = {"title":"Thank You!"}

return render(request,"home.html",context)


home.html

<h1>{{title}}</h1>
<form method='POST' action=''>{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit">
</form>


The problem is that I can't seem to understand how to save the data from the
checkboxes
and the
radiobuttons
. The form gets submitted successfully but when I look in the database the field of
check_boxes
is empty and the
radio_buttons
field shows a value "
False
" while I need my manual values as defined in the
CHOICES
list.

Answer

You have added two extra fields in your form which you have not mentioned in fields. Change your form like this.

class MyModelForm(forms.ModelForm):
    class Meta:
        model = FormData
        fields = ['text_area','email','full_name', 'check_boxes', 'radio_buttons']
        widgets = {
            'text_area': Textarea(attrs={'cols': 50, 'rows': 10}),
        }
    TYPE_CHOICES = [('s', 'small'),('m', 'medium'),('b', 'big')]
    check_boxes = forms.MultipleChoiceField(choices=TYPE_CHOICES, widget=forms.CheckboxSelectMultiple())

    CHOICES = [(1, 'One'),(2, 'Two'),(3, 'Three'),(4, 'Four')]
    radio_buttons = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())