Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean field not saving in Django form

Tags:

python

django

I have a form with radio buttons and text fields. When I submit the form, the boolean field does not get created in the record. The boolean field is supposed to be updated via the radio buttons. What could be the issue here?

Here is the relevant part of my forms.py file:

  CHOICES = (
        (1,'yes'),
        (0,'no')
    )

class ServiceForm(forms.ModelForm):
    one_time_service = forms.ChoiceField(required = True, choices = CHOICES, widget=forms.RadioSelect())

    class Meta:
        model = Service
        fields = ('one_time_service')

This is my models.py one_time_service field

one_time_service = models.BooleanField(default=False)

This is my views.py:

def create(request):
    if request.POST:
        form= ServiceForm(request.POST)
        if form.is_valid():
            service_obj = form.save(commit=False)
            service_obj.user_id = request.user.id
            service_obj.save()
            return render_to_response('services/service_created.html', 
                              {'service': Service.objects.get(id=service_obj.id)})
    else:
        form = ServiceForm()

    args= {}
    args.update(csrf(request))
    args['form'] = form

    return render_to_response('services/create_service.html', args )

Edit: Here is my create_service.html

<form action="/services/create" method="post" enctype="multipart/form-data">{% csrf_token %}
<ul>
{{form.as_p}}
</ul>

<input type="submit" name="submit" value="Create Service">
</form>
like image 722
Michael Smith Avatar asked Dec 10 '25 00:12

Michael Smith


1 Answers

I have no idea if this is the problem, but the line:

fields = ('one_time_service')

is wrong. That's not a single element tuple, that's a string with parens around it. Add a comma to make it a tuple:

fields = ('one_time_service',)

Edit: also, form.save() does not update any database records -- it creates a new one! That may be your problem.

like image 64
RemcoGerlich Avatar answered Dec 12 '25 14:12

RemcoGerlich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!