Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SQLite seems to ignore db_table parameter when running tests on MacOS but works fine on Ubuntu
So, the problem is when I'm running Django tests on MacOS I'm getting the following errors: Traceback (most recent call last): ... django.db.utils.OperationalError: no such table: main.estimates_estimate The above exception was the direct cause of the following exception: Traceback (most recent call last): ... raise CommandError( django.core.management.base.CommandError: Database file:memorydb_default?mode=memory&cache=shared couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run However, it passes if I change database to MySQL. Also, it passes on Ubuntu 20.04 with SQLite as DB backend. It just seems like db_table option of a model is ignored for some reason. class Estimate(models.Model): class Meta: db_table = "estimates" On Ubuntu db.sqlite3 has estimates table after the tests run is complete but on MacOS there is estimates_estimate. What I've tried I was looking for any possible difference of sqlite on Mac/Linux but couldn't find anything related. Also, I have tried to remove __pycache__ dirs and different Django versions (2.2 and 3.2). I've created a dummy app with the same file structure and … -
What is `*args` in a Django BaseCommand handle function for?
The signature of BaseCommand.handle is handle(*args, **kwargs). The documentation example only uses the kwargs argument. Are there cases/ways to define command arguments/options such that they will appear as positional arguments to the handle function? -
ERROR when i run pip install mssql-django or pip install pyodbc
Getting below error but got the solution also, you just do the following steps Go to https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyodbc Sownload suitable '".whl"' file (Make sure you choose the correct whl file. For example: If you are using Python 2.7 on a 64-bit machine choose '''pyodbc-4.0.32-cp310-cp310-win_amd64.whl'''.) run '''pip install pyodbc-4.0.32-cp310-cp310-win_amd64.whl''' and try again This was the error Running setup.py install for pyodbc ... error ERROR: Command errored out with exit status 1: command: 'C:\x\x\x\x\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\xxxx\x\x\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c\setup.py'"'"'; file='"'"'C:\Users\x\AppData\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\x\AppData\Local\Temp\pip-record-e9qbaui4\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\x\AppData\Local\Programs\Python\Python310\Include\pyodbc' cwd: C:\Users\x\AppData\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c Complete output (12 lines): running install running build running build_ext building 'pyodbc' extension creating build creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\src C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DPYODBC_VERSION=4.0.32 -IC:\Users\x\AppData\Local\Programs\Python\Python310\include -IC:\Users\x\AppData\Local\Programs\Python\Python310\Include -IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include -IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um /EHsc /T C:\Users\x\AppData\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c\src\pyodbc.h(19): fatal error C1083: Cannot open include file: 'windows.h': No such file or directory error: command 'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\cl.exe' failed with exi ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\x\AppData\Local\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\x\AppData\Local\Temp\pip-install-8j3hztgx\pyodbc_b5b6921fa34f4725a66d9248ff07177c\setup.py'"'"'; __file_n'"'"', open)(file) … -
set custom permission to model in Django
I have to set some permission to a model in Django because I have some operations in DRF and I need to know whether the user has permission to do it or not. My models : class Device(models.Model): type = models.ForeignKey(Type, on_delete=models.CASCADE) name = models.fields.CharField(max_length=36) ip = models.CharField(max_length=64, blank=True) password = models.CharField(max_length=62, blank=True) mac = models.CharField(max_length=17, blank=True) description = models.fields.TextField(max_length=600, blank=True) users = models.ManyToManyField(User,'users_device',through="UserMeta") status = models.BooleanField(default=False) def __str__(self): return self.name class UsersMeta(models.Model): type_choices = [ ("owner",'owner'), ('user','user'), ('admin','admin') ] user = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='UserMeta_devices') device = models.ForeignKey(Device,models.CASCADE,related_name='UserMeta_device') type = models.CharField(max_length=8,choices=type_choices) token = models.UUIDField(default=uuid4, editable=False, unique=True) join_time = models.DateTimeField(auto_now_add=True) last_activate = models.DateTimeField(null=True,blank=True) I need specific permission access to the Device model depending on the User model in the UserMeta model. in the UserMeta, I have some choices permissions like: owner,admin,user, so I need to say if this User has permission OWNER, or anything else can do it or not. I don't is correct or not, if do you know pls say to me -
React unable to read property of undefined
Can't figure out where my mistake is. Not able to map through to display the list of blog comments. I'm using django and react. From the code below, I tried to assess each blog post with comments. But I'm not able to get the comment property from the blog. If I do something like {blog.title} I get the title of the blog back on the browser. Since comments are associated with each post I try to get different properties of comment from the blog object (just as I specified in the code below) but the Value I'm getting is undefined. and have the following blog post and blog comment models. class BlogComment(models.Model): post = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, related_name="post_comment", null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_comment", null=True) name = models.CharField(max_length=200, null=True, blank=True) comment = models.TextField(null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) class BlogPost(models.Model): ... author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) body = models.TextField() dateCreated = models.DateTimeField(auto_now_add=True) And the serializers for both models are: class CommentSerializer(serializers.ModelSerializer): class Meta: model = BlogComment fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField(read_only=True) class Meta: model = BlogPost fields = "__all__" def get_comments(self, obj): comments = obj.comment_set.all() serializer = CommentSerializer(comments, many=True) return serializer.data <h2>{blog.title}</h2> <img src={blog.image} /> … -
Problem recovering django with pipenv after crash
I recently had a catastrophic hard drive failure and I had not pushed all of my recent commits to a remote repository (I have learned my lesson). Fortunately I did have a copy of most of my latest work. I recreated my local environment (I thought correctly but maybe not) and attempted to start the project with the files. When I run "pipenv shell" the env appears to activate and running "git branch" does show the two branches. However when I ran "python manage.py migrate" I received the following error: (sitefolder) user@users-MBP ohive % python manage.py migrate File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax When I run "python -V" it returns 2.7.18. The python version should be 3.9.6. When I do start pipenv shell in a folder without the old files, the correct version is returned. Any ideas about how I can get the pipenv to use the correct version of python? -
Django ninja token authentication with djoser
I have implemented CRUD with Django Ninja framework, but now I want auth in my app, I had installed and config Djoser, so now I can generate tokens, but I don't know how to verify in my CRUD's class AuthBearer(HttpBearer): def authenticate(self, request, token): if token == "supersecret": return token @api.get("/bearer", auth=AuthBearer()) def bearer(request): return {"token": request.auth} I shoud able to check token inside "AuthBearer" function, but I don't know how my repo (link) -
Django custom login not authenticating
I am creating a custom user creation. the register user is working but not managing to login, works fine in admin but not through my form. My loginclass in forms.py class LoginForm(forms.Form): email = forms.EmailField(label='Email') password = forms.CharField(widget=forms.PasswordInput) def __init__(self, request, *args, **kwargs): self.request = request super(LoginForm, self).__init__(*args, **kwargs) def clean(self): request = self.request data = self.cleaned_data email = data.get("email") password = data.get("password") qs = User.objects.filter(email=email) if qs.exists(): # user email is registered, check active/ not_active = qs.filter(is_active=False) if not_active.exists(): raise forms.ValidationError("This user is inactive.") user = authenticate(request, email=email, password=password) if user is None: raise forms.ValidationError("Invalid credentials") login(request, user) self.user = user return data This is from my views.py User = get_user_model() def login_page(request): form = LoginForm(request.POST or None) context = { "form": form } if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, email=email, password=password) if user is not None: login(request, user) else: # Return an 'invalid login' error message. print("Error") return render(request, "accounts/login.html", context) In my settings.py i have set LOGIN_REDIRECT_URL = '/' My html is here <form method="post"> {% csrf_token %} {{ form.non_field_errors }} {{ form.source.errors }} {{ form.source }} <div class="form-group"> <input class="form-control" type="email" name="{{ form.email.name }}" id="{{ form.email.id_for_label }}" {% if form.email.value != … -
Join Two Different Models, One 'unmanaged', in Django Without a Foreignkey Relation
I have the following two Django models: class Project(models.Model): identifier = models.CharField(max_length=128) target_value = models.CharField(max_length=64) ... Meta: managed='False' db_table='projects' class MainProjects(models.Model): mp_identifier = models.CharField(max_length=128) some_value = models.CharField(max_length=256) ... The database housing the Project model is actually off in a cloud database somewhere and is actually used by a completely different application written by a separate team. I need to be able to ask Django to pull a list of MainProjects and somehow annotate the target_value from the Project model into the QuerySet. I've tried using .extra() but the documentation is slim and the examples I've been able to find so far haven't worked for me. I'd also like to avoid using raw SQL if at all possible. Right now, I'm getting around the problem by using a management command I wrote for the Django application to go and fetch the target_value from the remote database and store it as MainProjects model attribute so that I can just reference it locally but - yuck. Thoughts? Suggestions? adsf -
Delete instance in django ModelForm
I am trying to delete an instance form in django ModelForm but it's not deleting, the update part is working perfectly though. my views.py: def update_component(request, pk): component = Component.objects.all() component_id = Component.objects.get(id=pk) form = ComponentModelForm(instance=component_id) if request.method=='POST' and 'form-update' in request.POST: form = ComponentModelForm(request.POST,request.FILES, instance=component_id) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) if request.method=='POST' and 'form-delete' in request.POST: form.delete() return redirect('/maintenance') context = { 'components': component, 'form': form, 'component_id':component_id, } return render(request, 'update_component.html', context) the delete form: <form class="component-delete-button"><input name="form-delete" type="submit" class="button1" value='Delete Component' /></form> -
Displaying the data from db in a table, one row/object at a time with Ajax python django
I am working on a Django project where I display a list of data. When the list is too long the page takes longer to load due to the amount of data that are displayed in that list. Instead of having a Django for loop to get all the data first and then display the page, I am thinking of first displaying the page and then loading all the data from the database via ajax in the background. In order to do that I was thinking of first displaying the whole template without the objects' data to load the page fast and then use an Ajax call to fetch the data with a view function, one object at a time. Is this viable and how can I do it? My datalist.py: from __future__ import absolute_import from __future__ import print_function from django.views.generic import ListView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required, user_passes_test from django.urls import reverse_lazy , reverse from django.apps import apps from django.http import HttpResponse , HttpResponseRedirect , Http404 from .models import * from .forms import * from .common import * from django.http import JsonResponse import json from django.forms.models import model_to_dict from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder … -
¿Cómo realizo una petición a mi aplicación desde el servidor en el que se encuentra alojada? [closed]
Estoy intentando hacer una petición a una aplicación que tengo desplegada en un servicio apache2 configurado en una maquina virtual ubuntu server, y para hacer la petición utilizo Python. Al momento de hacer la petición desde el navegador de algún equipo perteneciente a la red funciona común y corriente, el problema radica en el momento en el que intento hacer la misma petición pero estando dentro del servidor, bien sea en el navegador o ejecutando la petición por consola. A continuación dejo el error que me deja la consola del interprete de python, espero me puedan ayudar. >>> import requests >>> resp = requests.get('http://service-mails-customer.johannaortiz.local/') Traceback (most recent call last): File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/connection.py", line 175, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/util/connection.py", line 72, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 710, in urlopen chunked=chunked, File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 398, in _make_request conn.request(method, url, **httplib_request_kw) File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/connection.py", line 239, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "/usr/lib/python3.6/http/client.py", line 1285, … -
Error Deploying Project to Heroku With Git
I am trying to deploy my django project to heroku with git. I am runnning: git push heroku main And I get: error: src refspec main does not match any error: failed to push some refs to 'heroku' I also tried: git push heroku master That gave me: fatal: 'heroku' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I also tried git pull which gave me other errors. Nothing is working. -
Api testing issue with Json
Im new to the Django Rest Framework i think i did the serializer thing and views correctly, and it looks like this: class MyAnimalSerializer(serializers.ModelSerializer): class Meta: model = MyAnimal fields = ('id', 'user', 'name', 'animal', 'race', 'birthyear', 'color', 'sex', 'height', 'father', 'mother', 'doc_num',) class MyAnimalFormApi(APIView): permission_classes = (AllowAny,) def post(self, request): serializer = MyAnimalSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) Now when i try to test it with Postman { "data": { "name": "name", "animal": "dog"}, } i get { "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 1 column 47 (char 46)" } but it is enclosed in double quotes. Do you have any idea what's wrong or how to make it accessible only via {"name": "", "animal": ""} instead of nesting dictionary? -
ValueError: Cannot assign must be a instance
Because of a method to obtain the choices that I want to add to a field, it is giving me this error when saving the form. ValueError: Cannot assign "'17'": "Con_Transaccioncab.doc" must be a "Adm_Documento" instance. As I read in this post ValueError: Cannot assign object must be a instance the value is not being returned to me as an object, what other way can I do to retrieve the values in my get_choices method? get_choices method # Select de 3 tablas para obtener el nombre y valor del documento de la tabla adm_documento_periodo def get_choices(self): all_tipoaux = Adm_DocumentoPeriodo.objects.select_related('doc').filter \ (per=self.AIGN_PER_ID).select_related('doc__mod').filter(doc__mod__mod_codigov='CON').values("doc__doc_id", "doc__doc_nombre") DOC = [(d['doc__doc_id'], d['doc__doc_nombre']) for d in all_tipoaux] return DOC and this way I place it in the choicefield inside my form: self.fields['doc'] = ChoiceField(label='Acción: ', choices=self.get_choices(), required=False) any suggestion is welcome and appreciated -
How to associate newly created file model
I have this code, @receiver(post_save, sender=FileAnswer) def save_category_signals(sender, instance, **kwargs): file_types = ["image", "image-multiple"] file_type = instance.question.form_input_type if file_type in file_types: image_path = instance.body.path image = Image.open(image_path) img = image.convert('RGB') new_path = image_path.rsplit('.', 1) pdf = img.save(f'{new_path[0]}_{instance.id}.pdf', format="PDF") # os.remove(image_path) instance.body = pdf instance.save() # os.remove(image_path) # remove old image This code does not associate the file to the model instance. I have looked at django ContentFile and File. still can't really wrap my head around it as the examples aren't that helpful. -
Why am I getting "OperationalError: No Such Table" in Django
I am trying to store values in an sqlite database and them pull them from the database to use on my project using django models. There are two applications in my django project: 'main' and 'apply.' I have run migrate and makemigrations for both. When I save values to the model fields for 'main' it works fine. However, when I try to save values to the model fields for 'apply', I always get "utils.OperationalError: No Such Table apply_(model name)" I have set up a different database for my 'apply' models and the 'main' models use the default database. Relevant settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'apply': { 'NAME': 'apply_data', 'ENGINE': 'django.db.backends.sqlite3' }, } DATABASE_ROUTERS = ['django_webpage_project.routers.ApplyRouter'] projectname/routers.py class ApplyRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'apply',} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'apply' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'apply' return None def allow_relation(self, obj1, obj2, **hints): """ … -
How to use a modbus protocol with Django?
I'm using django to develop a monitoring system. This monitoring system uses the Modbus RTU communication protocol. A device can be used to use the inline form, as a device can have multiple records, this device is working properly. What happens is that I can't get the saved bank, because it needs the slave's data and the registration number to request the information. I'm using the mimimalmodbus library. Note: I can't get the slave_id and register_number from the database. My code is in Views.py in django instrument.serial.stopbits = 1 instrument.serial.timeout = 0.05 # seconds instrument.serial.xonxoff = False instrument.precalculate_read_size = False instrument.mode = minimalmodbus.MODE_RTU # rtu or ascii mode instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) a =instrument.read(register_number , slave_id) -
Migrating Homepage from Django to React
i built a Homepage using the Django templating engine and on one page is a js application i wrote. Now i moved to a Frontend <-> Backend architecture with React and Django-rest-framework. The Application i had in Django was served as a .html file with <script> tags for the js part. Now i moved to React and i'm serving the html elements through a React component and through React-helmet i'm adding the <script> tags for this specific page. The actual .js files reside in the /public folder of react. I thought i can replicate this way the old structure. But now i get Errors that the .js files don't find functions,variables etc. (The application consists of several js files). What could be the difference in this setup ? Thank you in advance for every answer :) -
Django filter, many queries in array
need an array where Q() object are added filter with many value Anime.objects.filter(Q(question__startswith='Who') & Q(question__startswith='What')) but need something like this val_arr = [] val_arr.append(Q(question__startswith='Who')) val_arr.append(Q(question__startswith='What')) Anime.objects.filter(val_arr) -
Django aws figure out how much current traffic my site can handle?
I have a django app running in aws EC2,my question is how to figure out, how much exact current traffic my site can handle and how to improve that? -
представление многочисленного выбора из формы django [closed]
Используя форму в Django я создал поле с многочисленным выбором. Как обработать в представлении полученный результат. Я каждый раз получаю только одно VALUES а хотелось получить комбинацию. есть код views.py from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import * def attl(request): if request.method == 'POST': form = AttlForma(request.POST) if form.is_valid(): #print form.cleaned_data['gender'] return HttpResponseRedirect('/thanks/') else: form = AttlForma() return render(request, 'attl/attl.html', {'form': form}) def attl_input(request, form=None): gender = request.POST['gender'] return render(request, 'resalt.html', { 'gender': gender, }) forms.py from django import forms from django.forms import RadioSelect HAS_BLED = [ ('a', 'Артериальная гипертензия (систолическое АД выше 160 мм рт. ст.)'), ('b', 'Нарушенная функция почек (диализ, трансплантация почки или креатинин сыворотки выше 200 мкмоль/л)'), ('c', 'Нарушенная функция печени (тяжелое хроническое заболевание или повышение билирубина в 2 раза и более выше верхней границы нормы в сочетании с повышением активности АсТ/АЛТ в 3 раза и более выше верхней границы нормы).'), ('d', 'Инсульт'), ('e', 'Кровотечение в анамнезе и/или предрасположенность к кровотечениям (в т.ч. анемия)'), ('f', 'Лабильное МНО (нестабильное/высокое или в терапевтическом диапазоне менее 60% времени)'), ('g', 'Возраст более 65 лет'), ('h', 'Злоупотребление алкоголем'), ('i', 'Прием препаратов, повышающих риск кровотечения (антиагреганты, НПВС)'), ] class AttlForma(forms.Form): gender = forms.ChoiceField(widget=forms.CheckboxSelectMultiple, choices=HAS_BLED, label="Пол") -
How to get django allauth google sign in to redirect to home page?
Hello I am using django and django all auth for authentication and am using the google feature so that when a user decides to sign in it authenticates with his google account then it will redirect him to the home page in my case to localhost:8000 in developement. But when I do try it does authenticate but instead of sending to localhost:8000 the home page it sends to this url: http://localhost:8000/accounts/profile/# not sure why. Here is my settings.py file. ACCOUNT_LOGOUT_REDIRECT_URL ='/' ACCOUNT_LOGIN_REDIRECT_URL ='task_list' ACCOUNT_SIGNUP_REDIRECT_URL = '/' SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } any help I would appreciate Thank you. -
Django-CKEditor Image Upload File Types
I have successfully installed Django CKeditor with Uploader but I have one problem I cannot find information about. When I select Upload I get the standard Windows file browser but it is set to all files. How can I configure CKUploader to just show supported image file types? Thanks. -
Issues with my +/- buttons inside an input-group
Wondering what I'm missing here... I'm whipping up a shop using django and have come across a real head-scratcher in my product details html. For some reason the +/- buttons don't work properly as they are not adding/subtracting quantities, and are adding the products straight to the shopping bag. Code for my product_detail.html: <form class="form" action="{% url 'add_to_bag' product.id %}" method="POST"> {% csrf_token %} <div class="form-row"> <div class="col-12"> <p class="mt-3"><strong>Quantity:</strong></p> <div class="form-group w-50"> <div class="input-group"> <div class="input-group-prepend"> <button class="decrement-qty btn btn-black rounded-0" data-item_id="{{ product.id }}" id="decrement-qty_{{ product.id }}"> <span class="icon"> <i class="fas fa-minus"></i> </span> </button> </div> <input class="form-control qty_input" type="number" name="quantity" value="1" min="1" max="99" data-item_id="{{ product.id }}" id="id_qty_{{ product.id }}"> <div class="input-group-append"> <button class="increment-qty btn btn-black rounded-0" data-item_id="{{ product.id }}" id="increment-qty_{{ product.id }}"> <span class="icon"> <i class="fas fa-plus"></i> </span> </button> </div> </div> </div> </div> <div class="col-12{% if s %}-12 mt-2{% endif %} mb-3"> <a href="{% url 'products' %}" class="btn btn-outline-black rounded-0 mt-5"> <span class="icon"> <i class="fas fa-chevron-left"></i> </span> <span class="text-uppercase">Keep Shopping</span> </a> <input type="submit" class="btn btn-black rounded-0 text-uppercase mt-5" value="Add to Bag"> </div> <input type="hidden" name="redirect_url" value="{{ request.path }}"> </div> </form> My JS to enable/disable and increment/decrement is : <script type="text/javascript"> function handleEnableDisable(itemId) { var currentValue = parseInt($(`#id_qty_${itemId}`).val()); var minusDisabled …