How To Use Toggle Switch With Django Boolean Field?
I have a work_experience model which contains 'is_working' field which is true when a user is still working at a company. On front end I'm using a toggle switch and I want to chang
Solution 1:
It is a bad idea to give null=True
parameter for CharField
.
If you want to change the boolean field value is_working
on click, you need to use Jquery.
I created an app named toggle
, so you need to replace it with your app's name.
here is the full code
urls.py::
from django.urlsimport path
from toggle.viewsimport home, toggle
urlpatterns = [
path('', home),
path('toggle/', toggle),
]
views.py:
from django.shortcuts import render
defhome(request):
w, created = Work_Experience.objects.get_or_create(id=1)
return render(request,'home.html', {'workexperiance': w})
from django.http import HttpResponse
from toggle.models import Work_Experience
deftoggle(request):
w = Work_Experience.objects.get(id=request.POST['id'])
w.is_working = request.POST['isworking'] == 'true'
w.save()
return HttpResponse('success')
home.html:
<divstyle="display:inline-block"><label>Currently working here?</label><labelclass="switch"><inputtype="checkbox"id="checkbox"value="{{workexperiance.is_working}}"><spanclass="slider round"></span></label></div><scriptsrc="https://code.jquery.com/jquery-3.3.1.js"></script><!-- Import Jquery Here--><scripttype="text/javascript">
$(document).ready(function() {
$('#checkbox').change(function() {
$.post("/toggle/", {
id: '{{workexperiance.id}}',
isworking: this.checked,
csrfmiddlewaretoken: '{{ csrf_token }}'
});
});
});
</script>
run: ./manage.py runserver
and visit: http://localhost:8000
when you click the Currently working here? check box, will instantly change the boolean field value "is_working".
Post a Comment for "How To Use Toggle Switch With Django Boolean Field?"