Boilerplate: Toggle A Django Checkbox With A Generic JavaScript Function Without Refreshing The Page
Introduction
This post shows how to use some JavaScript on a page to watch for changes to checkboxes on the page and send a request to Django to update the value without having to refresh the page. It assumes you already have a Django site/project set up by following the steps in Boilerplate: Create A New Django Site/Project , Boilerplate: Add Basic Template And Static File Handling In Django , and Boilerplate: Add Basic User Authencation To A Django Site .
It's also important to note that this version of the code doesn't work without javascript. I've got plans to make a more accessible version in the future.
Boilerplate Steps
-
Make sure you've started the Python venv and are in the directory with: manage.py
TODO: Write up how to make sure you're in the proper vecv
-
Create the app
terminal commands -
Make the todos templates directory
terminal commands -
Add the app to
=
site_config/settings.py - section update -
Update
site_config/urls.py for todossite_config/urls.py - full content replacement -
Make the todos urls file
todos/urls.py - new file to create -
Create the Todo model
todos/models.py - full content replacement -
Add the todos to the admin interface
todos/admin.py - full content replacement -
Update
todos/views.py todos/views.py - full content replacement -
Make the
todos/index.html page templatetodos/templates/todos/index.html - new file to create -
Run the todos migration
terminal commands -
Start the server
terminal commands -
Add todos
Go to the "todos" section of the admin interface and add a few Todos to play with. Tic the checkbox for "is_done" on some of them and leave it off for others.
(You'll need to login with your superuser admin username/password if you haven't already)
-
Visit the todos index page and play around with the checkboxes.
link
Endnotes
-
The JavaScript code is designed to be generic so that it can be used with any checkbox on the page. The only requirement is that the "data-href" be set up to point to a view that has a corresponding "toggle" function.
-
The checkbox is currently updated on the client side regardless of if the Django database succeeds with its update or not. TODO: Add error handling so that if Django doesn't respond or has an error the checkbox is reverted to its prior state after a short delay
-
TODO: Verify the 403 error status works properly if you try to use the checkbox without being logged in
-
This how-to is based off a single user site. This only checks to see if the user is authenciated, not for a specific user. Checking for a specific user is probably what you'd want to do to make sure users can't edit each other's stuff.