Utilizing the toggle switch functionality in Django with a boolean field implementation

My work_experience model includes an "is_working" field which is set to true when a user is currently employed at a company. I am using a toggle switch on the front end and would like to update the boolean field value for "is_working" with a click. What logic should I implement to use the toggle in Django?

Toggle switch

HTML

<div style="display:inline-block">
    <label>Currently working here?</label>
    <label class="switch">
        <input type="checkbox">
        <span class="slider round"></span>
    </label>
</div>

Model

class Work_Experience(models.Model):
    job_title       = models.CharField(max_length=100, null=True, blank=True)
    company         = models.CharField(max_length=100, null=True, blank=True)
    description     = models.CharField(max_length=300, null=True, blank=True)
    exp_start_date  = models.DateField(null=True, blank=True)
    exp_end_date    = models.DateField(null=True, blank=True)
    is_working      = models.BooleanField(default=False)

Answer №1

Avoid using the null=True parameter with the CharField as it is not a good practice.

To toggle the boolean field value is_working on click, Jquery must be used.

I developed an app called toggle, make sure to replace it with the name of your own app.

Below is the complete code:

urls.py::

from django.urls import path
from toggle.views import home, toggle

urlpatterns = [
    path('', home),
    path('toggle/', toggle),
]

views.py:

from django.shortcuts import render
def home(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
def toggle(request):
    w = Work_Experience.objects.get(id=request.POST['id'])
    w.is_working = request.POST['isworking'] == 'true'
    w.save()
    return HttpResponse('success')

home.html:

<div style="display:inline-block">
    <label>Currently working here?</label>
    <label class="switch">
        <input type="checkbox" id="checkbox" value="{{workexperiance.is_working}}">
        <span class="slider round"></span>
    </label>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script> <!-- Import Jquery Here-->
<script type="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

By clicking the Currently working here? checkbox, you can instantly toggle the "is_working" boolean field value.

Answer №2

If you're okay with the page being refreshed, this is how I would tackle it:

views.py:

from django.urls import reverse_lazy
from .models import Work_Experience
from django.shortcuts import redirect

def update_status(request,pk):
    status = Work_Experience.objects.get(id=pk)
    status.is_working^=True
    status.save()
    return redirect(reverse_lazy('index.html'))

urls.py

from django.urls import path
from .views import update_status

urlpatterns = [
    ...
    ...
    ...
    path('update-status/<int:pk>/', update_status, name='update-status'),
]

index.html

<div style="display:inline-block">
  <label>Currently employed?</label>
  <a href="{% url 'update-status' task.id %}">
    <label class="switch">
      <input type="checkbox">
      <span class="slider round"></span>
    </label>
  </a>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of the offcanvas button is not working correctly

I am currently utilizing the newest Bootstrap version of Offcanvas. Interestingly, there seems to be an issue with the close button functionality. When I click the "Add to Cart" button, the offcanvas displays properly. However, the "Add to Cart" button its ...

Issues with Submitting Form using Jquery, PHP, and Mysql

As a beginner, I find this task quite stressful. I want to create a simple chat system where users can send messages to the database without refreshing the page. Why isn't this code working (I've used similar code successfully before)..? <scr ...

What's causing these divs to be misaligned in various directions?

I am currently working with a front-end framework based on flexbox called Material-UI, and I have noticed that the layout of certain components, particularly the quantity control elements, appears to be different even though they all share the same styling ...

Cube.js Highlights of the Week and Month

How can I calculate metrics (count, sum) for specific time periods like Today/This Week/This Month/Last Month in Cube.js? I attempted to use rollingWindow but it did not provide me with the correct data. The documentation is a bit unclear to me. For a cle ...

Displaying Local Storage Data in Primeng Dropdown

I'm looking to implement local storage for the selected dropdown option, allowing users to see the same selection when they reload the page. Here's my dropdown: <p-dropdown [options]="languages" [(ngModel)]="selectedLanguage ...

How to Safely Merge Data from Several Excel Files into a Single Worksheet in Google Sheets using ExcelJS without Overwriting Existing Data

Just to clarify - I'm not a seasoned developer, I'm still a newbie at this. My current challenge involves transferring data from multiple Excel files located in one folder to a single worksheet in Google Sheets. To do this, I am utilizing excelJ ...

Can you explain the significance of the ">" symbol within CSS coding?

Seeking some quick points for those in the know. Can someone provide a thorough explanation of the meaning and proper usage of the > symbol? Appreciate it. ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

Tips for recovering lost files that were inadvertently deleted during a merging process

I attempted to delete all migration files on the master branch in Git, but encountered an error message: error: Merging is not possible because you have unmerged files. hint: Fix them up in the work tree, and then use 'git add/rm <file>' h ...

Step-by-step guide: Deploying your app to Heroku with Babel and ES6 support

I've been racking my brain trying to deploy the app on Heroku. The issue is with using ES6 along with Babel. I've come across numerous articles, but none have helped me resolve the problem. Even after building the app locally and attempting to ...

Troubleshooting: Issue with passing parameters in Wordpress ajax function

In my Wordpress Ajax implementation, I am facing an issue where the parameter value metakey: id is not being passed to $_POST["metakey"]. As a result, when I do a var_dump($_POST), it shows array(0) { }. If I manually set a static value for the variable i ...

Unleashing the Power of Node Js: Retrieving File Data and Form Data in POST Requests

When sending form data values using Postman, you can utilize a NodeJS server in the backend to handle the POST request. Here is an example of how to structure your code: require('dotenv').config(); const express = require('express'); co ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

When I use the AngularJS otherwise function, it sends me to the incorrect route

My routes are defined in the following way: $routeProvider .when('/settings', { templateUrl: 'settingsTemplateURL', controller: settingsCtrl }) .when('/profile', { templateUrl: 'profileTemplateURL', controll ...

creating an audio streaming application using child processes in nodejs

How can I effectively send a stream to a child process for streaming audio from a client to a server? I have successfully obtained the audio stream from a client. const ss = require('socket.io-stream'); const socketIo = require('socket.io& ...

Adapting the position of a table row in AngularJS based on the

I need assistance with creating a dynamic table-row that moves to indicate the current time in a table filled with timestamps. <table> <tr ng-repeat="timestamp in timestampArray"> <td>{{timestamp}}</td> </tr> ...

The dynamic change of a required field property does not occur

I am facing an issue where one of my fields in the form should be mandatory or not based on a boolean variable. Even if the variable changes, the field always remains required. I'm puzzled about why my expressionProperties templateOptions.required is ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

Using CSS styling to dictate how browsers display web content, specifically through setting font size measurements in EM

On different mobile devices and various browsers such as Internet Explorer and Mozilla, the font size in some divs does not appear consistent. Specifically, on a Samsung Galaxy S6. I am using EM units: I know it may not be ideal but I prefer this method a ...

Unforeseen outcomes discovered by stacking one div over another, all without relying on z-index

My current project involves two stacked divs, each measuring 100px by 100px. The bottom div includes a black border on top, as shown in this example. <div id="top"></div> <div id="bottom"></div>​ div { width: 100px; height ...