Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change CKEditor highligth theme on django?
I am not able to add styles in codes in posts. The style I put in works only when I'm going to edit in the Django admin site, but when I go to the post, the codes are in the default style. My code currently is: admin/base.html <script> var config = { extraPlugins: 'codesnippet', codeSnippet_theme: 'monokai_sublime', height: 356 }; CKEDITOR.replace ('body', config); </ script> blog/post_detail.html <link href="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/default.css' %}" rel="stylesheet"> <script src="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js' %}"></script> <script>hljs.initHighlightingOnLoad();</script> I also tried adding the first code to the posting file, but it did not work images: https://imgur.com/a/uyX3ytC -
Django Angular File Upload - Upload works in Postman but does not with angular 7
I have Django Backend that accepts File with other data as a request. When I use File Upload API from Postman to submit File and other form data. Postman Request It works fine and Prints <QueryDict: {u'csv': [<InMemoryUploadedFile: log_2018_10_09- 11_57_16_Summary_subject23_hrm.csv (text/csv)>], u'device_name': [u'Zephyr']}> and file successfully get stored. But when I am trying to do it with Angular it logs empty object. Below is my Angular Code. // HTML <input hidden type="file" id="csv" name="csv" accept=".csv" (change)="onFileChange($event)" #fileInput> // On Change Method onFileChange(evt: any) { if (evt.target.files && evt.target.files[0]) { const file = evt.target.files[0]; const reader = new FileReader(); reader.onload = () => { this.form.get('csv').setValue(file); }; reader.readAsText(evt.target.files[0]); this.uploadData.append('csv', this.form.get('csv').value); } } // On Submit Method onSubmit() { this.uploadData.append('device_name', this.form.get('device_name').value); this.backendService.insertCSV(this.uploadData).subscribe( response => { console.log(response); }, error => { console.log('error', error); } ); } // Call to Backend HttpUploadOptions = new HttpHeaders({ 'content-type': 'multipart/form-data', }); insertCSV(fileData): Observable<any> { return this.http.post('http://127.0.0.1:8000/upload/', { data: fileData, headers: this.HttpUploadOptions}); } Gives an Error on Console in Browser And Prints on Django {u'headers': {u'normalizedNames': {}, u'lazyUpdate': None}, u'data': {}} Please Help Me! -
Get value from one model to another with a custom migration?
I have a foreign key on a model referencing another model like so: class ModelA(CachingMixin, models.Model): fkCol = models.ForeignKey(ModelB, null=True, blank=True) With the above, I am able to express a one to one relationship. However there is now the need to support a one to many relationship for this, and I have recently created another model ModelAB. class ModelAB(models.Model): fkCol_A = models.ForeignKey(ModelB, related_name="modelB_modelA") fkCol_B = models.ForeignKey(ModelA, related_name="modelA_modelB") Is there a way to copy across (ideally when migrating) all values from ModelA > fkCol into the ModelAB > fkCol_A and populate ModelAB > fkCol_B values with the id of each record from ModelA? For example ModelA record with id=1 has a fkCol=10 needs to become ModelAB has fkCol_A = 10 and fkCol_B = 1 Is this possible? -
Django 'str' object has no attribute 'save'
I have a problem using Django in views.py....... the error in line post = text_headlines.save(commit=False) Exception Value: 'str' object has no attribute 'save' below is my code in forms.py, models.py and views.py thank you sorry I am new in Django still need time to learn forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('URL',) models.py from django.db import models # Create your models here. from django.conf import settings from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) URL = models.URLField(max_length=200) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views.py from django.shortcuts import render, redirect from .forms import PostForm from django.utils import timezone from django.shortcuts import render, get_object_or_404 from .models import Post from urllib.request import Request, urlopen as uReq from bs4 import BeautifulSoup as soup #Post.objects.get(pk=pk) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'post_detail.html', {'post': post}) def make_soup(website) : req = Request(website,headers = {'User-Agent' : 'Mozilla/5.0'}) uClient = uReq(req) page_html = uClient.read() uClient.close() page_soup = soup(page_html, 'html.parser') return page_soup def post_new(request) : if request.method == "POST": form = PostForm(request.POST) print(form) if form.is_valid(): url = form.cleaned_data['URL'] website = make_soup(url) headlines … -
NoReverseMatch at /accounts/profile/
I have a babysitter app I am working on. I can add and update the parent to the parent model with no problem. I can create and delete a kid but when I try to update a kid I get the following error. What am I doing wrong? I have been looking through examples and similar queries on this site but I still cant get it to work. [![ profile.html urls.py from django.conf.urls import url from .views import register, profile, logout, login, update_profile, update_profile_kid, create_profile_kid, delete_profile_kid urlpatterns = [ url(r'^register/$', register, name='register'), url(r'^profile/$', profile, name='profile'), url(r'^profile/update/$', update_profile, name='update_profile'), url(r'^profile/kids/update/(?P<id>\d+)$', update_profile_kid, name='update_profile_kid'), url(r'^profile/kids/delete/(?P<id>\d+)$', delete_profile_kid, name='delete_profile_kid'), url(r'^profile/kids/create/$', create_profile_kid, name='create_profile_kid'), url(r'^logout/$', logout, name='logout'), url(r'^login', login, name='login'), ] div class="modal fade" id="kiddyupdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Update child <strong>{{kid.name}}</strong></h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="{% url 'update_profile_kid' %}" method="post"> {% csrf_token %} <i class="fas fa-user fa-2x" aria-hidden="true"></i> <div class="form-group row"> <div class="col-sm-6 "> <input formControlName="name" name="name" type="text" value="{{kid.name}}" class="form-control form-control-lg" placeholder="Childs Name"> </div> </div> <i class="fas fa-mars fa-2x"></i><i class="fas fa-venus fa-2x"></i> <div class="input-group"> <select placeholder="Select a gender..." class="form-control chosen-select" style="width:350px;" tabindex="2" name="gender" type="text" value="{{kid.gender}}"> <option value="Select … -
Is it compulsory to end a url defined in urls.py. with '/'?
I have just started learning Django and want to know the reason behind a particular behavior the Django's polls application is showing. When I remove that '/' from the end of 'detail' URL path, I can access the details page of all questions except for the primary key(pk) 1. In case of pk 1, I am getting a 404 Error. It would be great if I will get an explanation. Thanks! Cheers! Here are the code files: polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] polls/views.py ....... ....... def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/details.html', {'question': question}) ....... ....... polls/templates/details.html <h1> {{ question.question_text }} </h1> <ul> {% for choice in question.choice_set.all %} <li> {{ choice.choice_text }} </li> {% endfor %} </ul> -
Is there a way to use iterator() in SlugRelatedfield queryset argument
Caching is happening in SlugrelatedField queryset argument , Is there a way to use iterator() in the queryset argument to avoid caching -
django forms create multiple of the same input with different names
I'm currently trying to create a form that takes multiple hidden inputs to collect data via javascript class NewCasePhotoForm(forms.Form): case_photo_1 = forms.CharField(required=False) case_photo_2 = forms.CharField(required=False) case_photo_3 = forms.CharField(required=False) case_photo_4 = forms.CharField(required=False) case_photo_5 = forms.CharField(required=False) case_photo_6 = forms.CharField(required=False) case_photo_7 = forms.CharField(required=False) case_photo_8 = forms.CharField(required=False) case_photo_9 = forms.CharField(required=False) case_photo_10 = forms.CharField(required=False) case_photo_11 = forms.CharField(required=False) case_photo_12 = forms.CharField(required=False) case_photo_13 = forms.CharField(required=False) case_photo_14 = forms.CharField(required=False) case_photo_15 = forms.CharField(required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i, field in enumerate(self.fields): self.fields[field].widget=forms.HiddenInput( attrs={ 'id': 'fileInput{}'.format(i+1) } ) Is there a better way to do this that is DRY? -
Django deploy - no images and css
So I have just deployed my website to my outer server. I coppied all files from my repo. I created virtualenv, database on server, created users, made migrations, migrated and ofc . Unlikely it seems that my images and css/js files are not found. Is it absolutely nessecarry necessary to install NginX (as it was told in tutorial) to get it done? On my localhost everything works fine... -
Django Graphene filter Foreign Model
I need to filter the object my request on the back-end base on permissions. For the following query : query { foos { id name bars { id name } } } There are permissions on foo and bar and I need to only return some foo and some bars. I know that I can use field lookups for foos class FooType(DjangoObjectType): class Meta: model = Foo class BarType(DjangoObjectType): class Meta: model = Bar class Query(object): foos = graphene.List(FooType) def resolve_foos(self, info, **kwargs): # id_list = some code to create a list of ids of possible foos return Foo.objects.filter(id__in=id_list) Say I have a list of possible bars, how can I do the same to filter on bar when requested by a graphql query ? -
Django, how serve media(users) files using nginx?
I'am struggling with my nginx configuration. Using docker-compose I deployed my Django app to vps. Static files works fine but I cant set up correctly media files. Below are my conf files: setting.py: STATIC_URL = '/static/' STATIC_ROOT = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' nginx conf file: upstream web { ip_hash; server web:8000; } # portal server { location /static/ { autoindex on; alias /static/; } location /media/ { autoindex on; alias /home/www/book_store/media/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } docker-compose.yml version: '2.1' services: nginx: #other commands volumes: - .:/code - ./nginx:/etc/nginx/conf.d - /static:/static - /media:/media depends_on: - web web: #other commands volumes: - .:/code - /static:/static - /media:/media error message when app trying to access media file (message from nginx container): ng01 | 2018/11/26 15:52:37 [error] 5#5: *6 open() "/home/www/book_store/media/default.png" failed (2: No such file or directory), client: XX.XX.XXX.XXX, server: localhost, request: "GET /media/default.png HTTP/1.1", host: "XXX.XXX.XX.XXX:8000", referrer: "http://XXX.XXX.XX.XXXX:8000/users/user/profile/" -
Bootstrapp Affix Function
If I copy the code from W3Schools to my webserver then the "sticky" menu works as long as I am referencing the CDN path for the script and stylesheet. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> If I change it to the location of the Bootstrap files that I have downloaded to the server then it doesn't work, although all other bootstrap styles and javascript functions work when referencing the local files. I have tried downloading the latest from Bootstrap as well. Sorry as I am probably missing something obvious, but is it possible to download the function and styles necessary for this to work? -
How to implement message notification in React App?
I am now building an application using React and Redux as the frontend and Django as the backend. What i am trying to realize is whenever an end user upload a file, all the end users that are related to this file should receive a notification. I am thinking of using websocket/socket.io but I am not sure if that works well with Django. Or any experience or suggestions of using any other technologies to implement the message notification function? -
How can I fix this error I'm getting when I want to run the server: 'django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.'
I am gettings this error when I'm trying to run the server (py manage.py runserver). I don't know what code I should upload because I think everything seems fine in my code... -
White Error Screen Appears when I try to update from form
I am getting a white error screen when I try to add an item via a form in python / django. I am trying to debug it but there is no information. Can somebody point me in the right direction? Models.py from __future__ import unicode_literals from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone # Create your models here. class UserProfile(models.Model): image = models.ImageField(upload_to='images', default='Upload Picture') user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) address1 = models.CharField(max_length=255, blank=True) address2 = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=20, null=True) county = models.CharField(max_length=100, null=True) postcode = models.CharField(max_length=7, null=True) biography = models.TextField(max_length=280,blank=True) email = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=10, blank=True) dob = models.CharField(max_length=10, blank=True) gender = models.CharField(max_length=1, blank=True) facebook = models.CharField(max_length=50, blank=True, null=True) twitter = models.CharField(max_length=50, blank=True, null=True) instagram = models.CharField(max_length=50, blank=True, null=True) class KidProfile(models.Model): parent = models.ForeignKey(User, related_name='kids') name = models.CharField(max_length=255, null=True, blank=True) dob = models.CharField(max_length=10, null=True, blank=True) gender = models.CharField(max_length=1, null=True, blank=True) needs = models.CharField(max_length=3, null=True, blank=True) def __str__ (self): return self.name views.py from django.contrib import messages, auth from accounts.forms import UserRegistrationForm, UserLoginForm, FullUserDetailsForm, KidDetailsForm from django.core.urlresolvers import reverse from django.shortcuts … -
Reduce Django serialization time
I am doing queries for roughly 100,000 rows with approximately 40 column each. The columns are of combination of float, integer, datetime, and char. The query time is about two seconds, and serialization is taking forty seconds or more, whereas response building is about two seconds too. I am wondering how can I reduce serialization time for Django models? -
gitlab-ci with docker-compose with django
I have a project on django, in which I plan to use docker-compose.yml as an image delivery to the production server, we also conduct local development via this file. Through docker-hub and bitbucket images are collected without any problems. At the same time, I can pull them out of the docker-hub registry and launch them into docker SWARM via a specially prepared docker-compose-prod.yml file. docker-compose.yml looks like: version: '3' services: web: build: . command: ['./init.sh'] volumes: - .:/code ports: - "8000:8000" I wanted to build images on my own Gitlab server and use the internal registry, but I can't get to tag images in the correct way. I cannot specify the image name through the "image" directive in docker-compose because I use it for local development, and if this directive is specified, the code will not run locally. Here is .gitlab-ci.yml: services: - docker:dind before_script: - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY build: stage: build image: host:4567/foreing_agent/foreing_agent:$CI_COMMIT_TAG script: - docker-compose -f docker-compose-test.yml up - docker-compose build - docker-compose push host:4567foreing_agent/foreing_agent:$CI_COMMIT_TAG Maybe someone can tell me how to build the process of assembling and deploying code on a production server? Can someone be able to give examples of using .gitlab-ci … -
How I can get attribute from queryset using prefetch_related in Django?
I have following model and extracted queryset using prefetch_related as below. queryset=Light.objects.filter(certificate__name="A").prefetch_related('zone__namingzone') From this queryset, I want to get following data set. {"naming1":lpd1,"naming2":lpd2...} However, when I try to extract attribute from queryset as below, I get create_reverse_many_to_one_manager for i in queryset: print (i.zone.namingzone) What I want to get is naming attribute in naming table. Could anyone tell me how I can extract this? models.py class Certificate(models.Model): name=models.CharField(max_length=20) class Zone(models.Model): zone=models.CharField(max_length=20) class Light(models.Model): certificate=models.ForeignKey(Certificate, on_delete=models.CASCADE,related_name='certificate') zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone') lpd=models.IntegerField() class Meta: unique_together = (('certificate', 'zone'),) class Naming(models.Model): zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='namingzone') naming=models.CharField(max_length=20) -
Twilio programmable chat re-creates token every time and conversation not contnuing after page refreshing
Here is my code that returns chat user token that should be used to participate in conversation powered by twilio programmable chat. Took source from here. def token(request): identity = request.GET.get('identity', request.user.email) device_id = request.GET.get('device', 'default') # unique device ID account_sid = settings.TWILIO_ACCOUNT_SID api_key = settings.TWILIO_API_KEY api_secret = settings.TWILIO_API_SECRET chat_service_sid = settings.TWILIO_CHAT_SERVICE_SID token = AccessToken(account_sid, api_key, api_secret, identity=identity) # Create a unique endpoint ID for the device endpoint = "MiniSlackChat:{0}:{1}".format(identity, device_id) if chat_service_sid: chat_grant = ChatGrant(endpoint_id=endpoint, service_sid=chat_service_sid) token.add_grant(chat_grant) response = { 'identity': identity, 'token': token.to_jwt().decode('utf-8') } return JsonResponse(response) But after one successful conversation between two users I get Error: Channel member limit exceeded (I've set up two users on channel limit because I don't need a conference chat feature). I think it's because of token re-creating every time when page is loading. How should I write my code to allow the user to participate in a chat with his old token? I've tried to store generated token by this way: def token(request): identity = request.GET.get('identity', request.user.email) device_id = request.GET.get('device', 'default') # unique device ID account_sid = settings.TWILIO_ACCOUNT_SID api_key = settings.TWILIO_API_KEY api_secret = settings.TWILIO_API_SECRET chat_service_sid = settings.TWILIO_CHAT_SERVICE_SID token = request.user.twilio_token endpoint = "Qiwi-chat:{0}:{1}".format(identity, device_id) if token: token = token.encode('utf-8') else: token … -
Django Send Email
I am making a parking system with the option Paid and Not Paid, and only when chosen form paid, I want the system to send an email with the payment confirmation. I am able to send the email via console, but via the system will not and does not present any error models.py from django.db import models from django.core.mail import send_mail import math PAGO_CHOICES = ( ('Não', 'Não Pago'), ('Sim', 'Pago') ) class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, blank=False, null=False,) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) veiculo = models.ForeignKey( Veiculo, on_delete=models.CASCADE, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) def horas_total(self): if self.checkout is None: return self.checkout == 0 else: return math.ceil((self.checkout - self.checkin).total_seconds() / 3600) def total(self): return self.valor_hora * self.horas_total() def __str__(self): return self.veiculo.placa def send_email(self): if self.pago is 'Sim': send_mail( 'Comprovante pagamento estacionamento', 'Here is the message.', 'estacioneaqui24@gmail.com', ['estacioneaqui24@gmail.com'], fail_silently=False, ) -
Apply Q object to one object
I have a complicated query in a Django model and I want to do two things: Get all objects that satisify the query Check if one object satisfies the query To do (1), I have a Q object encoding the query, and I just do Model.objects.filter(THE_QUERY) The query is something like THE_QUERY = Q(field_1__isnull=False) & Q(field_2__gte=2) & Q(field3=0) But I don't know how to reuse the query in THE_QUERY for (2). I want to have the predicate of the query in just one place and use that information to do (1) and (2), so that, if I ever have to change the query, both actions would do as expected. Is there a way to put the query in just one place? -
How to filter queryset by two lookups of the same field?
I'm building a tinder-like app. Here is a model represents review from one user to another: class Like(models.Model): like_from = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='outcome_likes') like_to = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='income_likes') is_positive = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.like_from} -> {self.like_to}' Now I'm trying to filter all matches and all I have is this code: def get_queryset(self): return CustomUser.objects.filter(income_likes__like_from=self.request.user, income_likes__is_positive=True)\ .filter(outcome_likes__like_to=self.request.user, outcome_likes__is_positive=True) # I also tried to go from the opposite side but # also had no idea how to get correct solution # Here should be some code to get intersection # of these two querysets's values lists # positive_likes_from = self.request.user.income_likes.all().filter(is_positive=True).values('like_from') # positive_likes_to = self.request.user.outcome_likes.all().filter(is_positive=True).values('like_to') But uncommented line here will return users that have any positive outcome likes with no guarantee that they will be addressed to the current user. I want to get a queryset of CustomUser model that have positive income and outcome likes with a current user on another side. Here is an solution of my problem that requires tons of SQL queries to the database: def get_queryset(self): positive_likes_from = self.request.user.income_likes.all().filter(is_positive=True) positive_likes_to = self.request.user.outcome_likes.all().filter(is_positive=True) result = [] for like in positive_likes_from: outcome_like_with_same_user_on_another_side = positive_likes_to.filter(like_to=like.like_from).first() if outcome_like_with_same_user_on_another_side: result.append((like, outcome_like_with_same_user_on_another_side)) return result -
how to access dictionary keys as index for list indexing in jinja2
i have a list selCategories and a dictionary categories. {{ selCategories }} // prints [1,1,0,0,1] {% for id,category in categories.items %} {{ selCategories.0 }} //prints 1 {{ selCategories.id }} //not printing anything {{ id }} //prints id values such as 1,2,3,4,5 <input type="checkbox" {% if selCategories.id == 1 %} checked {% endif %}>// empty checkbox {% endfor %} here selCategories=[1,1,0,0,1] categories={1:"Real",2:"education",3:"health",4:"food",5:"tourism"} how can i get the value of {{ selCategories.id }} so that i can use it in other html attributes -
A list and a form into the same django template
I have a one-page layout for a website, containing a list of latest posts in one section, and a contact form in another section. That means I need to feed both, the logic for the post list and the contact form, into the same template (home.html) I made it work as below, but that doesn't feel like the right solution... It's quite messy. Do you have a better approach? views.py def post_list(request): # Pull relevant posts from the database posts = Post.objects.filter(status='Published').order_by('-created') return posts def home_page(request): # Contact form logic if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(name, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found') messages.success(request, 'Mesage delivered') # Call the post_list() function posts = post_list(request) # Stuff it all into the home page template context = {'posts':posts, 'form':form} return render(request, "home.html", context) -
How I can delete Checked user in Django?
How I can delete Checked user in Django? After following answers on Stackoverflow, I've got the code below. However, I try to delete checked users from database by checked them then press delelte usig ajax but when press delete nothing happen at all also in server side it doesn't get 'POST' views.py def delete_list (request): if request.is_ajax(): selected_tests = request.POST['test_list_ids'] selected_tests = json.loads(selected_tests) for i, test in enumerate(selected_tests): if test != '': User.objects.filter(id__in=selected_tests).delete() return HttpResponseRedirect('/about') any.html <body> <button id="btn1" class="btn btn-round delete-btn" data-toggle="modal"> <i class="material-icons" action >delete</i> Delete </button> <div class="table-container"> <table id="fresh-table" class="table table-striped test-list"> <thead class="thead-table-list"> <tr> <th scope="col"> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" id="checkall" type="checkbox" value=""> <span class="form-check-sign"> <span class="check"></span> </span> </label> </div> </th> <th scope="col">Id</th> <th scope="col">username</th> <th scope="col">email</th> </tr> </thead> <tbody> {% for test in list_wait %} <tr data-id="{{ test.id }}"> <td> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input check-ele" type="checkbox" value=""> <span class="form-check-sign"> <span class="check"></span> </span> </label> </div> </td> <td>{{ test.id}}</td> <td>{{ test.username}}</td> <td>{{ test.email}}</td> </tr> {% endfor %} </tbody> </table> {% csrf_token %} </div> <script type='text/javascript'> $("#btn1").click(function(){ var selected_rows=[]; $('.test-list').find('tr').each(function(){ var row=$(this); console.log(row.find('input[type="checkbox"]').is(':checked')); if (row.find('input[type="checkbox"]').is(':checked')) { console.log(row.attr('data-id')); selected_rows.push(row.attr('data-id')); }; }); var selected_rows = JSON.stringify(selected_rows); $.ajax({ url: "{% url 'delete_list' %}", type: 'POST', data: …