Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How are messaging apps like Whatsapp or Messenger built?
I'm trying to build a mobile messaging app like Whatsapp and don't know where to start. In the first place, I don't know how messaging apps send messages between users. What type of protocol do they use? Do they use websockets? Do they use some sort of long polling? I mean what I really want to know is how the server works and is there a name to this sort of communication? FYI, I was looking to try and build a messaging app with a Django (something like django channels) server and React native for the mobile app. Thanks for reading. -
Loading specific foreign key attribute in Django Template
Devs, I have a 2 Models and one of them have a foreign key attribute as a reference to the other. Now I am trying to view both objects in my Template. class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_context_data(self, **kwargs): context = super(ItemDetailView, self).get_context_data(**kwargs) context['markets'] = Market.objects.all() # And so on for more models return context In my template I just want the exact market for my product I tryed something like this: {% for market in markets %} // or {% for object.market in markets %} {% if market.market == object.market %} >> Do smth if conditions match << {% endif %} {% endfor %} In the loop I get strings like x1, x2, x3 and object.market have the value x1. So I just want to output x1. -
How do you add a LoginRequiredMixin when there's an inconsistent method resolution?
I have the following urls.py file: urlpatterns = [ path('', views.index, name='index'), path('account/', include('django.contrib.auth.urls'), name="login"), path('signup/', views.SignUp.as_view(), name='signup'), path('polls/<int:pk>/', views.DetailView.as_view(), name='detail'), path('polls/<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('polls/<int:week_id>/vote/', views.vote, name='vote'), ] And the following views: @login_required def index(request): return HttpResponse("Hello, there my frined") class SignUp(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' class DetailView(LoginRequiredMixin, DetailView): model = Week template_name = "detail.html" # Problem is here class ResultsView(LoginRequiredMixin, DetailView): model = Week template_name = 'results.html' For some reason the LoginRequiedMixin in the ResultsView class produces the following error: File "/Users/user/Projects/cafeteria/weeklydesert/urls.py", line 3, in <module> from . import views File "/Users/user/Projects/cafeteria/weeklydesert/views.py", line 25, in <module> class ResultsView(LoginRequiredMixin, DetailView): TypeError: Cannot create a consistent method resolution order (MRO) for bases LoginRequiredMixin, DetailView This is my results.html <h1>Week of: {{ week.coming_monday }}</h1> <ul> {% for choice in week.choice_set.all %} <li>{{ choice.desert_choice }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'detail' week.id %}">Vote again?</a> The code runs fine when removing the mixin form ResultsView, what's wrong with the code? -
Best way to use Python classes for creating Stripe objects and handling errors
I have a Django application that integrates with Stripe. Per the Stripe documentation, I am following their recommendation to use try/except clauses to handle any errors that might arise during the process of creating customers, products, prices, etc. To keep things DRY, I have made a base Python class from which object-specific subclasses inherit. This way I can customize the create_method of each subclass to create a particular object, but still keep all the error handling in one place (the parent class). This all seems to be working fine, but I'm wondering if anyone has any feedback or suggested improvements for this approach? Thanks! import stripe from django.conf import settings stripe.api_key = settings.STRIPE_SECRET_KEY class StripeObject(): """ Base class for all Stripe objects (e.g., Customer, Product, Price) """ create_method = None def __init__(self, common_kwargs={}, instance_kwargs={}): self.common_kwargs = common_kwargs self.instance_kwargs = instance_kwargs def handle_error(e): try: print('Code is: %s' % e.code) print('Message is: %s' % e.user_message) except KeyError: print('One of the following keys was not found in the error response:\ncode or user_message.') def create(self): try: return self.create_method(**self.common_kwargs, **self.instance_kwargs) except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly self.handle_error(e) except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to … -
Different title and description tags for Django site with pagination
I have a web site running on django and use pagination for some of my pages. Search engines demand different title and description tags for every page. Is it possible somehow differentiate title and description tags for different pages with similar name (https://bratus.net/listings/?page=2), for example using part of pagination code in title ? Thank you !!! -
How can I force users to enable full screen while taking the test using javascript
I am developing a quiz app for my academic project. whenever a user attempts a quiz, he must enable fullscreen mode before taking the test. If he do so then only he can attempt the quiz. If he disable the full screen mode by pressing esc key then a warning message should be shown and he cannot attempt the quiz until he reenables full screen mode. -
django ORM join two model on a foreign key
The title might be misleading, I'm not sure on how to express my problem I have two models declared this way: class Record(models.Model): # autogen id as primary key name = models.ForeignKey(Product, on_delete=models.DO_NOTHING) value = models.FloatField() date = models.DateTimeField() class Integration(models.Model): # autogen id as primary key action = models.FloatField() on_record = models.ForeignKey(Record, on_delete=models.DO_NOTHING) I have one Record per hour per day on an entire year, thus 24*365. For each Record, there are exactely ten (10) Integrations, each having their distinct action. What I need is a QuerySet on Record that has an "extra column" with the average of the related 10 Integration's actions. So Record | id| name | value | date | |---|------|-------|------| | 1 | A | 120.00| 2020-01-01 00:00 | | 2 | B | 85.00 | 2020-01-01 01:00 | Integration | id | action | on_record | |-----|--------|-----------| | 0x1 | 7.00 | 1 | | 0x2 | 2.00 | 1 | | 0x3 | 9.00 | 1 | | ... | ... | ... | | 0x10 | 8.41 | 1 | | 0x11 | 8.99 | 2 <-- next Record | What I need id name value date integration_avg_action 1 A 120.00 2020-01-01 … -
'User' object has no attribute 'is_staff'
I am working with user authentication system where I created a user registration model using AbstractBaseUser. then I create super User using terminal . But when I go the admin and write email and password there . It gives me the error that: 'User' object has no attribute 'is_staff' My models.py file is: from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager SUBJECT_CHOICES = ( ('math','Math'), ('physics','Physics'), ('chemistry','Chemistry'), ) class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") user_obj = self.model(email=self.normalize_email(email), full_name=full_name) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,full_name=None,password=None): user = self.create_user(email, full_name=full_name,password=password) return user def create_superuser(self,email, full_name=None,password=None): user = self.create_user(email, full_name=full_name, password=password) return user class User(AbstractBaseUser): full_name = models.CharField(max_length=255, blank=True, null=True) sur_name = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255 ,unique=True) choose_subject = models.CharField(choices=SUBJECT_CHOICES , max_length=100) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) time_stamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] object = UserManager() def __str__(self): return self.full_name my forms.py file is: class RegisterForm(forms.ModelForm): # A form for creation new user included all all the required fields including repeated password password1 = forms.CharField(label='Enter Password' , widget=forms.PasswordInput ) password2 … -
Django auth_views.PasswordResetView keep sending raw html email
I'm trying to send a custom email template with the reset token. But it keeps sending raw HTML no matter what I do. I have previous experience of doing exactly the same thing without any problem with the Django and Django rest framework. Here's how I did it, urls.py ... path('password_reset', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html', html_email_template_name='registration/html_password_reset_email.html', email_template_name = 'registration/password_reset_email.html, ), name='password_reset' ), folder structure ... templates |-- registration |-- html_password_reset_email.html |-- password_reset_email.html |-- ... ... Email template {% load i18n %}{% autoescape off %} {% load static %} <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> @media screen and (max-width: 720px) { body .c-v84rpm { width: 100% !important; max-width: 720px !important; } body .c-v84rpm .c-7bgiy1 .c-1c86scm { display: none !important; } body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-pekv9n .c-1qv5bbj, body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-1c9o9ex .c-1qv5bbj, body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-90qmnj .c-1qv5bbj { border-width: 1px 0 0 !important; } body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-183lp8j .c-1qv5bbj { border-width: 1px 0 !important; } body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-pekv9n .c-1qv5bbj { padding-left: 12px !important; padding-right: 12px !important; } body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-1c9o9ex .c-1qv5bbj, body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-90qmnj .c-1qv5bbj { padding-left: 8px !important; padding-right: 8px !important; } body .c-v84rpm .c-ry4gth .c-1dhsbqv { display: none !important; … -
Adding groups in form django | 'RegisterUserForm' object has no attribute 'groups'
SubjectTeacher model where SubjectClass and TeacherUser has been passed. -
How to find average datetime in a object?
I created an approval system. I have an ApprovalProcess model. This model has end_date and begin_date. And end_date - beginning_date is duration time. I have several ApprovalProcess models I want to find what is the total average duration time of all ApprovalProcess objects. I cannot find the difference between end_date and begin_date. It gives an error: TypeError at /approval/logs unsupported operand type(s) for +: 'int' and 'datetime.timedelta' How can I do it? models.py class ApprovalProcess(models.Model): ... begin_date = models.DateTimeField(null=True) end_date = models.DateTimeField(null=True) ... views.py def log_records(request): ... approval_list = ApprovalProcess.objects.filter(user_id=request.user) delta = 0 approval_list = ApprovalProcess.objects.filter(customer__company=request.user.company) for approval_object in approval_list: delta = abs((approval_object.end_date - approval_object.begin_date).days) ... -
viewing all emails with javasript in django
Im trying to show all objects from Emails model on page. Im trying to make it by creating new elements. I would like the solution to be using javascript. I cant find what the problem may be.I tried inspecting the code, and the elements created with javascript were not there. And yes, there are objects in my Emails module. views.py: import json from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.db import IntegrityError from django.http import JsonResponse from django.shortcuts import HttpResponse, HttpResponseRedirect, render from django.urls import reverse from django.views.decorators.csrf import csrf_exempt from .models import User, Email def index(request): # Authenticated users view their inbox if request.user.is_authenticated: return render(request, "mail/inbox.html") # Everyone else is prompted to sign in else: return HttpResponseRedirect(reverse("login")) @csrf_exempt @login_required def compose(request): # Composing a new email must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # Check recipient emails data = json.loads(request.body) emails = [email.strip() for email in data.get("recipients").split(",")] if emails == [""]: return JsonResponse({ "error": "At least one recipient required." }, status=400) # Convert email addresses to users recipients = [] for email in emails: try: user = User.objects.get(email=email) recipients.append(user) except User.DoesNotExist: return JsonResponse({ "error": f"User with email … -
I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf
views.py def resume(request,id): user_profile=Profile.objects.get(pk=id) template= loader.get_template("Resume/profile.html") html= template.render({'user_profile':user_profile}) options={ 'page-size':'Letter', 'encoding' : 'UTF-8', } pdf= pdfkit.from_string(html,False,options) response= HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition']= 'attachment' return response profile.html {% extends "Resume/layout.html" %} {% block body %} <h2>{{ user_profile.full_name }}</h2> <h2>{{ user_profile.job_title }}</h2> <hr> <h2>{{ user_profile.email }}</h2> <h2>{{ user_profile.phone }}</h2> <h2>{{ user_profile.home_adress }}</h2> <hr> <p>Summary</p> <p> {{ user_profile.work_experience }}</p> <p> {{ user_profile.skills }}</p> <hr> <p>Education</p> <ul> <li> {{user_profile.diplomes}} </li> </ul> <hr> {% endblock %} ![this is th pdf i get ][1] [1]:( https://i.stack.imgur.com/PXlt3.png) I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf can anyone help me with this, i don't know what the problem is -
Add a class field in Django <UL>
<ul> {% topic_menu_full federation "Federation" %} {% topic_menu_full our-school "Our School" %} {% topic_menu_full learning "Learning" %} {% topic_menu_full children "Children" %} {% topic_menu_full parents "Parents" %} </ul> I want to add class to only the last one in the list, for example .red the last one. -
In production mode, react helmet async is not working and How react helmet async works?
Recently, I started playing with meta tags in react. After some research, I found that react-helmet-async is the best library to set meta tags for each page. however, I wanted to want set meta tags for few pages conditionally. I setup metatags for two pages differently, take a look... index.js ReactDOM.render( <React.StrictMode> <HelmetProvider> <App/> </HelmetProvider> </React.StrictMode>, document.getElementById('root') ); pageOne.jsx componentDidMount(){ axios.get('/getTrack/',{params: {id: this.props.match.params.id}}) .then((res) => this.setState({trackData: res.data, isLoading: false})) .catch((err) => console.log(err)) } render() { return ( this.state.isLoading? <div className="page-loader"> <Helmet> {/* Page sittings */} <meta charset="utf-8" /> <meta name="theme-color" content="#000000" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {/* Primary Meta Tags */} <title>Loading...</title> </Helmet> </div> : <div className="main-page"> <Helmet> {/* Page sittings */} <meta charset="utf-8" /> <meta name="theme-color" content="#000000" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {/* Primary Meta Tags */} <title>{this.state.trackData.title}</title> <meta name="title" content={this.state.trackData.title}/> <meta name="description" content={this.state.trackData.desc}/> {/* Open Graph / Facebook */} <meta property="og:type" content="website"/> <meta property="og:url" content="https://example.com/"/> <meta property="og:title" content={this.state.trackData.title}/> <meta property="og:description" content={this.state.trackData.desc}/> <meta property="og:image" content="/logo192.png"/> {/* Twitter */} <meta property="twitter:card" content="summary_large_image"/> <meta property="twitter:url" content="https://example.com/"/> <meta property="twitter:title" content={this.state.trackData.title}/> <meta property="twitter:description" content={this.state.trackData.desc}/> <meta property="twitter:image" content="/logo192.png"/> </Helmet> </div> ) } pageTwo.jsx <Helmet> {/* Primary Meta Tags */} <title>XYZ</title> <meta charset="utf-8" /> <meta name="title" content="xyz"/> <meta name="theme-color" content="#000000" /> <meta name="viewport" … -
Expression contains mixed types: DecimalField, IntegerField. You must set output_field
I am trying execute a query with multiple annotates and i keep getting the output_field required error where as i am already writing that. I have tried to change the output to decimal but does not work. Any idea? My targeted code count = ShareAllocation.objects.filter(session_key=self.storage.request.session.session_key). \ values('share_type__id', 'share_type__code', 'share_type__type'). \ annotate(share_count=Sum('share_type__id')). \ annotate(total_shares=Sum('number_of_shares')). \ annotate(total_paid=ExpressionWrapper(F('amount_paid') * F('total_shares'), output_field=models.IntegerField)).\ annotate(total_unpaid=ExpressionWrapper( F('amount_unpaid') * F('total_shares'), output_field=models.IntegerField ) ).\ count() if count == 0: return False else: return True -
I want to send back a list and a dictionary in django for my site in php
I want to send back a list and a dictionary in django for my site in php,I have a python script that flips a list and an dictionary exemple: list=[ [name,ip,country][name2,ip2,country2] ] dictionary={"name":"A","name2":"B"} I want to put them in jango format and use them in my php code. thanks you!! -
Filtering of user related data in Django / DRF
I am working on a Django application with the Django Rest Framework. I try to do things the Django/DRF way. It is already a non-trivial service, so I have extracted the relevant details from the code to show here. I have the following apps: Report Cluster User The User model, serializer, and view can be considered to be standard for this question. Report class Report(models.Model): slug = models.CharField(unique=True, max_length=100, blank=False, null=False) name = models.CharField(max_length=100, blank=False) clusters = models.ManyToManyField(Cluster, blank=True, related_name='report_clusters') users = models.ManyToManyField(User, blank=True, related_name='report_users') class ReportSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Report fields = ("slug", "url", "name", "clusters") read_only_fields = ('slug', 'clusters') lookup_field = "slug" extra_kwargs = { 'url': {'lookup_field': 'slug'}, 'clusters': {'lookup_field': 'slug'}, } class ReportViewSet(viewsets.ModelViewSet, LoginRequiredMixin): queryset = Report.objects.all() serializer_class = ReportSerializer permission_classes = (permissions.IsAuthenticated, IsAdminUserOrReadOnly) lookup_field = "slug" def get_queryset(self): """Only show user related items.""" return Report.objects.filter(users__id=self.request.user.id) Cluster class Cluster(models.Model): slug = models.CharField(unique=True, max_length=100, blank=False, null=False) name = models.CharField(max_length=100, blank=False, unique=True) users = models.ManyToManyField(User, blank=True) observers = models.ManyToManyField(User, blank=True, related_name='cluster_observer') class ClusterTreeSerializer(serializers.HyperlinkedModelSerializer): # children = serializers.SerializerMethodField() class Meta: model = Cluster fields = ('url', 'slug', 'name') read_only_fields = ('url', 'slug') lookup_field = "slug" extra_kwargs = {'url': {'lookup_field': 'slug'}} class ClusterViewSet(viewsets.ModelViewSet, LoginRequiredMixin): queryset = Cluster.objects.all() serializer_class = ClusterTreeSerializer … -
Could not translate host name “postgres” to address
i a working with django, docker and postgree as db , when i try to compile my project with: docker-compose up --build, i got this error "Could not translate host name “postgres” to address". Please Need help ? -
Favicon not loading in Django
I can't seem to get my favicon to load at all, I have the image in my static folder, all other images load fine on both local and production environments, and I can load the favicon as an image no problem. It just doesn't load as the actual favicon. I have the code to load favicon in the head tag (and all other static files that are loaded there are working, such as style sheets and meta tags). I have {% load static %} at the top of the page as well. Here is my code in the tag which attempts to set the favicon: <link rel="icon" type="image/png" href="{% static 'stockdeepdive/images/favicon.ico' %}"> <link rel="icon" type="image/png" sizes="192x192" href="{% static 'stockdeepdive/images/android-icon-192x192.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'stockdeepdive/images/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="96x96" href="{% static 'stockdeepdive/images/favicon-96x96.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'stockdeepdive/images/favicon-16x16.png' %}"> The images are all located within static folder, then stockdeepdive folder, then finally images folder. All other images are working good. Im not getting any errors in console, but I'm also not seeing any "GET" request for the favicons. Any help greatly appreciated, I've spent hours trying to figure this out. -
What are the dependencies for django-allauth python:3.8.3-alpine Dockerfile
I have a Dockerfile, docker-compose.yml, requirements.txt defined below for a django project. The Dockerfile uses python:3.8.3-alpine and the docker-compose.yml have a db service that uses postgres:12.0-alpine image. I made sure that the dependencies are defined in the Dockerfile as required. However, it seems to me that django-allauth require extra dependencies. I have tried for days to fix this issue but get an error that says This package requires Rust >=1.41.0. ERROR: Failed building wheel for cryptography. I haved pasted the whole error for reference sake. Any help will be much appreciated. Thanks in advance. #requirements.txt Django>=3.1.5,<3.2.0 gunicorn>=20.0.4,<20.1.0 psycopg2-binary>=2.8,<2.9 Pillow>=8.1.0,<8.2.0 django-allauth>=0.44.0,<1.0.0 #Dockerfile # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev \ && apk add libffi-dev libressl-dev \ && apk add --no-cache jpeg-dev zlib-dev libjpeg # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] #docker-compose.yml version: '3.7' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - … -
Embed matplotlib bar graph in html page
I am trying to embed a matplotlib bar graph in html page. I have tried almost everything. here's my code- views.py- def result(request) plt.bar(x,h) plt.xlabel("Personality") plt.ylabel("course") plt.show() return render(request,'result.html') -
Django doesn't read JWT token
My django backend use JWT token for user auth. I store recieved token in 'Authtorization' header using axios. Everything works well. But I noticed problem when I open any link in new tab (ctrl+click), after this I get on to auth page but I still have the token in my header. Why does it happen? -
Empty space below navbar in header
I'm creating a web app using Python - Django. I'm currently working on the front-end part and below my navbar in the header section is a ton of free white-space that I can't seem to get rid off. Also I want my background image behind the whole page, can't seem to get my head around how to do that. It's always either above the body or below it. Any clues? My html with bootstrap: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <link rel="stylesheet" type="text/css" href="{% static 'styles/stylesheet.css' %}"> <link rel="icon" href="{% static 'images/favicon.ico' %}"> <title> Milk - {% block title_block %}Milk Students{% endblock %} </title> <!-- Bootstrap core CSS --> <link href="https://getbootstrap.com/docs/4.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- Custom styles for this template --> <link href="https://getbootstrap.com/docs/4.2/examples/dashboard/dashboard.css" rel="stylesheet"> </head> <body> <header> <div class ="container"> <!-- Navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark py-1"> <a class="navbar-brand p-2" href="{% url 'milk_app:home' %}">MilkStudents</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto" > <li class="nav-item"><a class="nav-link" href="{% url 'milk_app:home' %}">Home</a></li> … -
Get All checkbox value selected , Table row wise using AJAX : DJANGO
I have code which should select all rows from a table whose checkbox is selected . So first i will describe my table structure . So here there will be many rows , so i should select which server i need and which operation i should perform . So if i have two server ABC and BCD , if i want to perform start operation for ABC and Stop for ABC , i should select respective servers from first checkbox and associated operations from the checkbox on same row as the server name . and i should pass all values row wise to views.py for performing other operations . so currently I wrote a code , which give me the value even if i didn't checked the checkbox . And am not able to figure out issue . Can any anyone help me. this is my AJAX call : $("[name=ButtonSubmit]").click(function(){ var myarrayServer = []; var myarrayStart = []; var myarrayRestart = []; var myarrayStop =[]; var message = " "; $(".form-check-input0:checked").each(function() { var row = $(this).closest("tr")[0]; message += row.cells[1].innerHTML; message += " " + row.cells[2].innerHTML; message += " " + row.cells[3].innerHTML; message += " " + row.cells[4].innerHTML; var checkedValue = …