[Answered ]-Django checkboxes not saving to database: What am I doing wrong?

1👍

Your form action is malformatted:

action="{% url 'tracker:bookSteps'                    }" // Change this
action="{% url 'tracker:bookSteps' book_page.book_id %}" // to this

this.form.submit() also does not take any parameters:

onclick="this.form.submit({book_id: book_page.book_id})" // Change this
onclick="this.form.submit()"                             // to this
👤aaron

0👍

Exactly that, you don’t save the records to the database, you should use:

if data['ISBNsent']:
    progress = Progress(
        ISBNsent=True,
        ISBN_sentDate=timezone.now(),
        book=book_page,
    )
    progress.save()

or:

if data['ISBNsent']:
    progress = Progress.objects.create(
        ISBNsent=True,
        ISBN_sentDate=timezone.now(),
        book=book_page,
    )

Your check should however check if 'ISBNsent' is an element of request.POST, since a checkbox is not sent if not checked, so:

if 'ISBNsent' in data:
    progress = Progress.objects.create(
        ISBNsent=True, ISBN_sentDate=timezone.now()
    )

Note: It is better to use a Form [Django-doc]
than to perform manual validation and cleaning of the data. A Form will not
only simplify rendering a form in HTML, but it also makes it more convenient
to validate the input, and clean the data to a more convenient type.

Leave a comment