Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
write script in django template
I have a database of ads and want to show them in a template. The datetime of these ads are in the milliseconds since epoch format and must be converted to the 'a time ago' format. I wrote this code in views.py and working well for just one ads. How can I change that to working for all ads in database? class crawler(generic.ListView): paginate_by = 12 model = models.Catalogue template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) for cat in models.Catalogue.objects.all(): if cat.source_id == 3: date = float(cat.datetime) d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f') d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f') now = datetime.datetime.now() time_ago = timeago.format(d_datetime, now, 'fa_IR') context['time_ago'] = time_ago return context How can I write this code in script? -
How to get appended/prepended element value in Django POST.?
I have a form in which initially 3 fields are there, 'Job Category', 'Manpower Quantity and 'Country'. I am using Jquery to prepend elements more than 4 times. Now I want to fetch the prepended elements values using the Django POST method. Plz, help me as i am new in Django. Thanks in advance. -
How can i regroup some columns in django?
Here is my view : clients = models.Client.objects.all() sellin = models.Sellinvoice.objects.filter(client_id__in = clients) It is my template: <table> <tr> <th>ClientName</th> <th>Price</th> </tr> {% regroup sellin by client.name list %} {% for cl in list %} <tr> <td>{{ cl.grouper }}</td> <td>{{ cl.client.price }}</td> </tr> {% endfor %} </table> Result is: ClientName Price (if user have two invoice this column added automatically) john doe 30000 30000 (problem) maria 12000 david 43000 Some user have two invoice and I can regroup ClientName but how can regroup Prices? -
My docker image in google cloud run doesn't read css file
I create my website with Django composed with docker. GitHub is here . When I compile this docker image, the app shows a webpage with CSS, on the other hand when I deploy this docker image on the google cloud run then it shows only HTML file, I mean it doesn't include CSS file so that it shows just text. Does anyone know why this happened? If someone knows, please let me know the ways to show my website with styles. -
Attach information from another model to a model with Django
On my Django chat application, users have access rights to a Company and access rights to some chat rooms of this company. They need a Company access right to be granted access to a chat room. When a user connects to a room, I would like to display in a column all users which have a company access right for the related company and for each of those if they have an access to the chat room (checkboxes) so that users can easily be added or removed from the chatroom by clicking on the checkbox. To display this list of users, I can manually build a Python object with all company access rights, and for each of those add a field indicating if the person also has access to the room. Isn't there a pure Django way to do that ? Here are my models: class CompanyAccessRight(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name="accessrights") company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="authorizedpeople") class Room(models.Model): acessrights = models.ManyToManyField(CompanyAccessRight, through='RoomAccessRight') class RoomAccessRight(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='accessrightsforroom') accessrights = models.ForeignKey(CompanyAccessRight, on_delete=models.CASCADE, related_name='chatarforcompanyar') -
Stock Code Generator with Django & Database
I am coding a program for the my company about the automatic stock code generator webservice. Normally, i am taking the stock codes from the excel file, but at the moment i am going to use a postgresql database. Our company stock code's has meaningful number(if material is Black code is like this "Black.1", if its also has different color it's like this "White.1" I have started a app with Django and i have created this script's models. But i can't understand how can i proceed. Thanks in advance. -
How we use AJAX in Django to send video file of script.js to views.py?
This is Script.js downloadButton.addEventListener('click', () => { const blob = new Blob(recordedBlobs, {type: 'video/mp4'}); const url = window.URL.createObjectURL(blob); a.style.display = 'none'; a.href = url; a.download = 'test.mp4'; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 100); /* On submiting the form, send the POST ajax request to server and after successfull submission display the object. */ $("#downloadButton").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call $.ajax({ type: 'POST', url: "{% url 'post_video' %}", data: serializedData, success: function (response) { // on successfull creating object // 1. clear the form. $("#downloadButton").trigger('reset'); }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) }) }); Views.py def Video_Recording(request): return render(request, "HafrApp/Start_Interview.html") def post_video(request): print('hy') # request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": form = FriendForm(request.POST) fs = FileSystemStorage() filename = fs.save(form.name, form) print('hy') return JsonResponse({"error": ""}, status=400) Urls.py path('post/ajax', views.postFriend, name = "post_friend"), path('Start_Interview', views.Video_Recording), Start_Interview.html <!DOCTYPE html> <html> <head> <title>Media Recorder in Javascript</title> {% load static %} <link rel="stylesheet" href="{% static 'Candidate/main.css' %}" /> </head> <body> <div … -
Cannot assign "'7'": "Appointment.your_service" must be a "Service" instance
I'm working on a project "Beauty Parlour Management System" and I got this error (Cannot assign "'7'": "Appointment.your_service" must be a "Service" instance.) anyone here can help me, please. When I am filling a book appointment form then I got this error. models.py class Service(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(default=0) image = models.ImageField(upload_to='uploads/productImg') class Appointment(models.Model): your_name = models.CharField(max_length=100) your_phone = models.CharField(max_length=10) your_email = models.EmailField(max_length=200) your_service = models.ForeignKey('Service', on_delete=models.CASCADE, default=1) your_date = models.DateField() views.py def appointments(request): if request.method == 'GET': return render(request, 'core/bookappointment.html') else: your_name = request.POST.get('your-name') your_phone = request.POST.get('your-phone') your_email = request.POST.get('your-email') your_service = request.POST.get('your-service') your_date = request.POST.get('your-date') details = Appointment( your_name = your_name, your_phone = your_phone, your_email = your_email, your_service = your_service, your_date = your_date) details.save() return render(request, 'core/appointments.html') -
Why does .gitignore downloads files during pull and creating conflicts when modified?
So this problem is at two fronts. One locally and one on ec2 instance where I'm trying to pull from github. I force pushed (git push origin main -f) from local to github with all folders and files. I pulled it on server using git pull origin main. Then I added static_files/ and .env to my .gitignore locally and got it committed and git push origin main. Now I deleted static_files folder and .env from github. So the first problem is when I now take a git pull origin main, it deletes the folder and .env. Secondly, I modified .env and .gitignore on my server using sudo nano but even when .env is ignored it shows conflicts during git pull origin main as, CONFLICT (content): Merge conflict in .gitignore CONFLICT (modify/delete): .env deleted in 6d0cc45a49f2faf3bbbacd and modified in HEAD. Version HEAD of .env left in tree. Automatic merge failed; fix conflicts and then commit the result. -
After using models.Model on my class Im getting 'ImproperlyConfigured' error Django
I just started a new project in django, I run the command 'django-admin startproject + project_name', and 'python manage.py startapp + app_name'. Created a project and app. I also added my new app to the settings: settings pic After that I tried to create my first module on 'modules.py' file on my app, but when I do it and run the file, it gives me this error message: Error message The entire error message says: " django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. " I created a few projects before, and never had this problem. I discovered that if I dont use the 'models.Model' on my class, it does not gives me this error. No error message on this case Someone knows that it is about, and why it gives this error? I didnt change anything on settings, just added the app. -
Trending system
I'd like to know if it is possible to implement some kind of trending system to my Django project. Suppose that we have a Django website, like Instagram, and we need to show an user the most followed users in that platform, how would that be possible if we had a lot of people using the website? Should I use something like Elasticsearch for making big queries faster or should I keep going with only Django itself? I am using Postgresql and I'm really new to Django, anyway, thank you for any answers -
How to showcase quantity with a ManyToMany field django?
Created a recipe app which showcased the list of ingredients and instructions for a recipe, however with Django current form of displaying manytomany relationships, how do I say: 1kg of tomato, 1 oz of water, etc my models: class IngredientList(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class RecipeList(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField('IngredientList') instructions = models.TextField(max_length=400) amount = models.IntegerField() my views: from django.shortcuts import render from .models import IngredientList, RecipeList def index(request): ing = RecipeList.objects.all() context = {'ing': ing} return render(request, 'myrecipes/home.html', context) -
Customer with multiple addresses, can have only one primary address
I created an app 'customerbin' inside my Django install. I need to create/edit/delete customers who can have multiple addresses where only one address can be primary. If a customer is deleted, all the addresses that belong to that customer need to be deleted as well. If a new customer is created we can't pick an address from another customer. models.py: from django.db import models class Address(models.Model): street = models.CharField(max_length=100) number = models.IntegerField(null=True) postal = models.IntegerField(null=True) city = models.CharField(max_length=100) country = models.CharField(max_length=100) is_primary = models.BooleanField(null=False) geo_lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) geo_lon = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Customer(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True) vat = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) address = models.ForeignKey(Address, on_delete=models.CASCADE) admin.py: from django.contrib import admin from . import models # Register your models here. admin.site.register(models.Customer) admin.site.register(models.Address) How can I make it so that: An address is exclusively linked to one customer? All addresses are deleted when I delete a customer? Only one address is primary for a customer? -
Display ManytoMany Django
trying to display all the ingredients that are associated to a recipe, however: my models: class IngredientList(models.Model): name = models.CharField(max_length=100) class RecipeList(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField('IngredientList') instructions = models.TextField(max_length=400) amount = models.IntegerField() my views: from django.shortcuts import render from .models import IngredientList, RecipeList def index(request): ing = RecipeList.objects.all() context = {'ing': ing} return render(request, 'myrecipes/home.html', context) my template: <div class="card-body"> <h4>{{ details.name}} <span class="badge badge-info">{{details.cuisine}}</span></h4> <p class="card-text">Ingredients: {{details.ingredients}}</p> <p class="card-text">Instructions: {{details.instructions}}</p> <p class="card-text">This makes {{ details.amount}} meals</p> </div> my output is "myrecipes.IngredientList.None" -
Is it possible to fill in ready-made data through inputs to the JsonField() at Django?
Good afternoon dear friends! Can you tell us more about JsonField() at Django? There is an idea, and it seems that it can be created with the help of json. I would like to create ready-made keys, for example, url_file_1, url_file_2 and more, and also for them size_file_1, size_file_2 in the form of simple inputs, and upon completion of the writing of the article, display them separately according to the keys to the template. Does anyone have an example of solving such a problem? -
'CategoryDetailView' object has no attribute 'get_object'
I am setting up my CategoryDetailView for my CRM. Then this error occurred: 'CategoryDetailView' object has no attribute 'get_object' here's my code sectrion from views.py: class CategoryDetailView(LoginRequiredMixin, generic.ListView): template_name = "clients/category/category_detail.html" context_object_name = "category" def get_context_data(self, **kwargs): context = super(CategoryDetailView, self).get_context_data(**kwargs) clients = self.get_object().client_set.all() context.update({ "clients": clients }) return context Here's my models.py class Client(models.Model): first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) organization = models.ForeignKey(UserProfile, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) class Category(models.Model): name = models.CharField(max_length=30) # New, Tapped, Active, Closed organization = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.name Thanks in advance! -
Not able to make a GET request to the django REST API backend for the id=1 article, from axios in reactjs
I have a frontend application built using reactjs and django rest framework is used to serve this frontend using APIs. The django rest APIs are working fine, I have checked via Postman. When I make a GET request to http://127.0.0.1:8000/articles/, I get the list of articles, and when I click on one of them, it is supposed to take me to the article detail page for that specific id of the article. This is done by making a GET request to http://127.0.0.1:8000/articles/id. The problem is, when I make GET request for id=2,3,4,5,... , it works fine. But when the request is made for id=1, it fails with the error Access to XMLHttpRequest at 'http://127.0.0.1:8000/articles/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Please note that there is no such error for articles/2 or articles/3 and so on. I have allowed the relevant host in django settings.py file. This is the code I have for the article detail page. function ArticlePage(props) { const [MainArticle, setMainArticle] = useState({}); const {id} = useParams() const url = 'http://127.0.0.1:8000/articles/'+id; useEffect(() => { console.log("hello world"); axios.get(url) .then((response) => { setMainArticle(response.data); console.log(response.data); }) .catch((error)=>console.log(error)) }, [url]); return … -
How to make SVG auto scale to the div container - vertical scaling not working
I wrote a SVG that I want to scale to width and height of the parent container. This is scaling horizontally, but not scaling vertically. How to make it work? Do I need to modify the SVG or the CSS? SVG made using svgwrite: import svgwrite def test(request): dwg = svgwrite.Drawing('test.svg', profile='tiny', size=('100%', '100%')) dwg.viewbox(minx=0, miny=0, width=500, height=300) # dwg.stretch() # dwg.fit(horiz='center', vert='middle', scale='slice') dwg.add(dwg.line((0, 0), (0, 500),stroke=svgwrite.rgb(153, 153, 153, 'RGB'), fill='none')) dwg.add(dwg.line((0, 0), (500, 0),stroke=svgwrite.rgb(153, 153, 153, 'RGB'), fill='none')) dwg.add(dwg.line((500, 300), (0, 300),stroke=svgwrite.rgb(153, 153, 153, 'RGB'), fill='none')) dwg.add(dwg.line((500, 300), (500, 0),stroke=svgwrite.rgb(153, 153, 153, 'RGB'), fill='none')) dwg.save() return render(request, 'test.html', context={'svg': dwg }) .resizeme { resize: both; margin: 10px; padding: 0; height: 300px; width: 500px; background-color: #fffdf9; border: hsl(0, 0%, 67%); overflow: hidden; box-shadow: 0 2px 8px rgba(60,65,70,0.1); border-radius: 3px; } <div class="resizeme"> <img src="data:image/svg+xml,<svg baseProfile=&quot;tiny&quot; height=&quot;100%&quot; version=&quot;1.2&quot; viewBox=&quot;0,0,500,300&quot; width=&quot;100%&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:ev=&quot;http://www.w3.org/2001/xml-events&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;><defs /> <line fill=&quot;none&quot; stroke=&quot;rgb(153,153,153)&quot; x1=&quot;0&quot; x2=&quot;0&quot; y1=&quot;0&quot; y2=&quot;500&quot; /> <line fill=&quot;none&quot; stroke=&quot;rgb(153,153,153)&quot; x1=&quot;0&quot; x2=&quot;500&quot; y1=&quot;0&quot; y2=&quot;0&quot; /> <line fill=&quot;none&quot; stroke=&quot;rgb(153,153,153)&quot; x1=&quot;500&quot; x2=&quot;0&quot; y1=&quot;300&quot; y2=&quot;300&quot; /> <line fill=&quot;none&quot; stroke=&quot;rgb(153,153,153)&quot; x1=&quot;500&quot; x2=&quot;500&quot; y1=&quot;300&quot; y2=&quot;0&quot; /></svg>"> </div> -
Django - how to return JSON responses instead of HTML during authentication?
I'm in the process of building a Vue SPA that will use the standard Django Session Authentication, since the Django app and the Vue app will be on the same server and same domain. I've always used django-allauth for everything authentication related, but the problem in this case is that authentication is not handled by Django templates, but i use AJAX to send POST requests to Django to register, sign in and everything else. Is there any way to make Django-Allauth or Django send JSON responses instead of standard HTML and redirects? Here is an example POST request from my code that i use to login: bodyFormData.append('csrfmiddlewaretoken', this.csrf_token) bodyFormData.append('login', 'root'); bodyFormData.append('password', 'Stest'); axios({ method: "post", url: "http://127.0.0.1:8000/accounts/login/", data: bodyFormData, withCredentials: true, headers: {"Content-Type": "application/json"}, }) .then(function (response) { //handle success }) .catch(function (response) { //handle error }); This seems to work fine, it logs me in but the response is HTML and from the network tabs i can see that django tries to redirect me to another page (because that's what it does when authentication is handled by Django templates). Is there any way i can make it send only JSON responses? Do i have to override some view or … -
How do I return my plot graph after return another result in flask python
I need some help, the situation is I m able to return the new CSV file but unable to return the plot graph to another page, and I did separate the return under different scenarios. Does anyone can point out what should I do to my code? or perhaps give me some tips, Thanks in advance! app.py @app.route('/transform', methods=["POST"]) def transform_view(): if request.method == 'POST': if request.files['data_file']: f = request.files['data_file'] if not f: return "No file" stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None) csv_input = csv.reader(stream) stream.seek(0) result = stream.read() df = pd.read_csv(StringIO(result), usecols=[1]) #extract month value df2 = pd.read_csv(StringIO(result)) matrix2 = df2[df2.columns[0]].to_numpy() list1 = matrix2.tolist() # load the model from disk model = load_model('model.h5') dataset = df.values dataset = dataset.astype('float32') scaler = MinMaxScaler(feature_range=(0, 1)) dataset = scaler.fit_transform(dataset) look_back = 1 dataset_look = create_dataset(dataset, look_back) dataset_look = np.reshape(dataset_look, (dataset_look.shape[0], 1, dataset_look.shape[1])) predict = model.predict(dataset_look) transform = scaler.inverse_transform(predict) X_FUTURE = 12 transform = np.array([]) last = dataset[-1] for i in range(X_FUTURE): curr_prediction = model.predict(np.array([last]).reshape(1, look_back, 1)) last = np.concatenate([last[1:], curr_prediction.reshape(-1)]) transform = np.concatenate([transform, curr_prediction[0]]) transform = scaler.inverse_transform([transform])[0] dicts = [] curr_date = pd.to_datetime(list1[-1]) for i in range(X_FUTURE): curr_date = curr_date + relativedelta(months=+1) dicts.append({'Predictions': transform[i], "Month": curr_date}) new_data = pd.DataFrame(dicts).set_index("Month") ##df_predict = pd.DataFrame(transform, columns=["predicted value"]) … -
How to run coroutine function when use sync_to_async in django?
I have a class method that calls _post method as async using sync_to_async in django. but when I test the method inside of Django shell, it does not even run my async _post function and return coroutine object instead. Here is my method: @classmethod def add_event(cls, data): async_post_request = sync_to_async( cls._post, thread_sensitive=True ) response = async_post_request( url=cls.ADD_EVENT, data=data, headers=cls.get_headers(), json_response=False, ) return response Screen of Django shell: -
Django filter id with another model
I Have two model then filtering with another model witout foreignkey like this in the views.py file model1 = apps.get_model('home', 'DataSiswa') model2 = apps.get_model('home', 'DataSekolah') datasiswa1 = model1.objects.filter(statussiswa="Aktif") ids = datasiswa1.values_list('id', flat=True) datasiswa2 = model2.objects.filter(id__in=ids) but object in model datasiswa2 just returning same datasiswa1 data, with only last datasiswa1__id repeated How to iterate that? Or any possible way to queryset multi model then get all the data (both model are one to one relationship with ID) -
Implementing live search using JavaScript and Django
I am trying to make a livesearch feature similar to when you conduct a google search. The search queries cafes in my database by name. I have gotten the functionality to the point where if the whole search value matches a cafe's name in the database it shows up for the user but would like to make it so the search value is checked letter by letter (assuming this is the best way to do a live search). Here is what I have: $("#search-box").keyup(function() { search() }); function search(){ let searchTerm = document.getElementById("search-box").value; $.ajax({ type: 'GET', url: '/electra/search/', data: { 'search_term':searchTerm }, success: function (data) { console.log(searchTerm); //refer to below function for the running of this loop $("#search-results").text(data); } }); }; views.py: def search(request): template_name = 'testingland/write_image.html' search_term = request.GET.get('search_term', None) print(search_term) qs = mapCafes.objects.filter(cafe_name = search_term) return JsonResponse([ [cafe.cafe_name, cafe.cafe_address] for cafe in qs ], safe=False) I have been playing around with the qs filter but can't figure out the best way to approach this. -
Crop/Mask WMS geoTIFF using Polygon
I am building a geospatial webapp with Django. If I have a polygon of class django.contrib.gis.geos.polygon.Polygon, how can I crop/mask a rectangular geoTIFF (gathered via a WMS request; dataset) to the shape of polygon? I've gone down the route of using rasterio to load the TIFF into memory (based on answers to this question), but being new to GIS within Python, I'm not sure this is the best approach to take for my crop/mask requirement. I'm happy to consider any and all solutions to this question. My call to the Corine landcover service, which returns a rectangular tiff: from owslib.wms import WebMapService from rasterio import MemoryFile wms = WebMapService('https://copernicus.discomap.eea.europa.eu/arcgis/services/Corine/CLC2018_WM/MapServer/WMSServer?request=GetCapabilities&service=WMS',version='1.1.1') bbox = (0.823974609375, 52.1081920974632, 1.1700439453125, 52.3202320760973) img = wms.getmap(layers=['12'], srs='EPSG:4326', size=(600, 500), bbox=bbox, format='image/geotiff') with MemoryFile(img) as memfile: with memfile.open() as dataset: print(dataset.profile) And a polygon used to crop/mask dataset: polygon = "SRID=4326;POLYGON ((0.9063720703125029 52.32023207609735, 0.8239746093749998 52.10819209746323, 1.170043945312496 52.14191683166823, 1.170043945312496 52.31351619974807, 0.9063720703125029 52.32023207609735)" Interestingly--and I'm not sure if this will cause cropping issues--when I call dataset.profile I see that there is no CRS information, despite defining srs in getmap and returning a geoTIFF: {'driver': 'PNG', 'dtype': 'uint8', 'nodata': None, 'width': 600, 'height': 500, 'count': 3, 'crs': None, 'transform': Affine(1.0, 0.0, 0.0, … -
On off toggle switch in django BooleanField
I am building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to change BooleanField into On and Off Toggle Switch. But Failed many times. models.py class Using(models.Model): user = models.ManyToManyField(User,default='') choice = models.BooleanField(default=True,blank=True) template.html <style> .switch { width: 50px; height: 17px; position: relative; display: inline-block; } .switch input { display: none; } .switch .slider { position: absolute; top: 0; bottom: 0; right: 0; left: 0; cursor: pointer; background-color: #e7ecf1; border-radius: 30px !important; border: 0; padding: 0; display: block; margin: 12px 10px; min-height: 11px; } .switch .slider:before { position: absolute; background-color: #aaa; height: 15px; width: 15px; content: ""; left: 0px; bottom: -2px; border-radius: 50%; transition: ease-in-out .5s; } .switch .slider:after { content: ""; color: white; display: block; position: absolute; transform: translate(-50%,-50%); top: 50%; left: 70%; transition: all .5s; font-size: 10px; font-family: Verdana,sans-serif; } .switch input:checked + .slider:after { transition: all .5s; left: 30%; content: ""; } .switch input:checked + .slider { background-color: #d3d6d9; } .switch input:checked + .slider:before { transform: translateX(15px); background-color: #26a2ac; } </style> <label class="switch"> <input type="checkbox" name="choice" id="id_choice" /> <div class="slider"></div> </label> What have i tried :- I tried many CSS and HTML methods BUT nothing worked for …