Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use the onsubmit function in Django to switch pages?
I'm trying to create a page that, once a form submit button is clicked, will redirect to the home page. I'm using the 'onsubmit' function for that, but it isn't working. HTML code {% extends 'base.html' %}{% load static %} {% block head %} <link rel="stylesheet" href="{% static 'login.css' %}" /> <script src="{% static 'login.js'}"></script> {% endblock %} <!-- page code --> {% block pagename %} <p>SIGN IN</p> {% endblock %} {% block content %} <div class="contentContainer"> <p>Please enter your competition ID:</p> <form class="form" onsubmit="pageSwitch()"> <input type="text" id="entry" placeholder="ID ENTRY HERE..."> <a name="container"></a> <input type="submit" id="entrySubmit" value="SUBMIT"> </form> </div> {% endblock %} JS Code function pageSwitch(){ window.location.replace("{% url 'home %'}"); } urls.py Code from django.contrib import admin from django.urls import path from files import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('test/', views.test, name='test'), path('', views.login, name='login'), path('home/', views.home, name='home'), path('leaderboard/', views.lboard, name='lboard'), path('scorecard/', views.score, name='score'), path('submit/', views.submit, name='submit'), path('base/', views.base, name='base'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 'views.py' Code from django.shortcuts import render # Create your views here. def test(request): return render(request, 'test.html') def base(request): return render(request, 'base.html') def login(request): return render(request, 'login.html') def home(request): return render(request, 'home.html') def lboard(request): return render(request, 'leaderboard.html') def … -
after uploading a file in Django Firebase "Storage", how can I download that file by clicking the HTML button?
when I upload any type of file by clicking the "Send" button, that file will be uploaded, and get the URL of that file. then renders the URL through the context in HTML. But here, my problem is when I click the "Download" button the file opens up in that tab instead of being downloaded. How can I solve this? Where I am use python-pip Pyrebase4==4.6.0 Firebase Connection class Firebase: def __init__(self): firebaseConfig = { 'apiKey': "_____", 'authDomain': "____", 'projectId': "___", 'storageBucket': "_____", 'messagingSenderId': "______", 'appId': "___________", 'measurementId': "_______", 'databaseURL': '__________', 'serviceAccount': 'service.json' } firebase = pyrebase.initialize_app(firebaseConfig) self.fireStorage = firebase.storage() My Views from django.shortcuts import render from django.core.files.storage import default_storage from . models import Firebase def index(request): if request.method == 'POST': file = request.FILES['file'] file_save = default_storage.save(file.name, file) # save the file as temporary firebaseObj = Firebase() firebaseObj.fireStorage.child(f'files/{file.name}').put(f'medias/{file.name}') URL = firebaseObj.fireStorage.child(f'files/{file.name}').get_url(None) delete = default_storage.delete(file.name) # delete the temporary file return render(request, 'index.html', context={'fileurl':URL}) return render(request, 'index.html') In HTML <div> <form method="post" action="{% url 'index' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file" id="fileid" required> <br> <button type="submit">Send</button> </form> <a href="{{ url }}" download> <button> Download Now </button> </a> </div> -
CORS failed for React + Django
For my django application, I use django-cors-headers to enable cross-platform requests. I use the library in that way. settings.py ... ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'accounts', "corsheaders", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:3000"] CORS_ALLOWED_HEADERS = list(default_headers) + ['content-type'] ... That's how i do post requests let response = await fetch("http://localhost:8000/auth/signup/", {"method": "POST", "body": { "username" : "test", "password": "test" }, "headers" : { 'Conent-Type': "Application/json" }, } ) Error: Access to fetch at 'http://localhost:8000/auth/signup/' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Request header field conent-type is not allowed by Access-Control-Allow-Headers in preflight response. I also checked the OPTION requests that the browser sends to check the 'cors' headers and discovered that the response allows the 'content-type' header. There is response headers for option request. Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: http://127.0.0.1:3000 Access-Control-Max-Age: 86400 Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Thu, 16 Feb 2023 12:36:55 GMT Server: WSGIServer/0.2 CPython/3.9.2 Vary: Origin I looked into how to enable cors for Django. -
Getting error "'list' object is not callable" for authentication_classes
I have following method: @action(detail=False, permission_classes=(IsOwnerOrReadOnly,)) @debugger_queries def get_xyz(self, request, pk=None): # ... Inside this method, request.user was always AnonymousUser. I felt that it was because I did not specify any kind of authentication for this method. I skipped through codebase and found other developers using decorator. So, I tried by adding a decorator @authentication_classes([TokenAuthentication,]) as follows: @action(detail=False, permission_classes=(IsOwnerOrReadOnly,)) @debugger_queries @authentication_classes([TokenAuthentication,]) def get_xyz(self, request, pk=None): # ... But it started me giving 'list' object is not callable error on this newly added line. What I am missing here? PS: I am trying to hit url from postman. I have logged in my website from the browser, copied csrftoken and sessionid from browser to postman. -
Django and Docker Compose access media folder between containers
I'm working on a docker-compose app using Django and a container to check images validity, here's the project structure: |-- backend | |-- backend | | |-- asgi.py | | |-- celery.py | | |-- __init__.py | | |-- settings.py | | `-- urls.py | |-- manage.py | |-- media | | `-- temp | | `-- image.png | |-- profiles |-- docker-compose.yml |-- Dockerfile |-- README.md |-- requirements.txt Here's the docker-compose configuration of django and nsfw: app: build: . volumes: - .:/app env_file: - ./.env/prod.env ports: - 8000:8000 depends_on: - database nsfw: image: eugencepoi/nsfw_api logging: driver: none ports: - "5000:5000" depends_on: - app environment: - PORT=5000 And here's the code I'm using to exchange the image between containers: url = "http://app:8000/media/temp/image.png" response = requests.get(f"http://nsfw:5000/?url={url}") And here's the settings.py configuration: MEDIA_URL = "/media/" # prints app/backend/media MEDIA_ROOT = os.path.join(BASE_DIR, "media") And finally urls.py: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I'm using django in production mode, but I can't use NGINX to serve images because they are shared locally by containers. Are there errors in my code? Thank you -
Combine two django models with shared ids into a single viewset
I have two django models in two independent apps, who use the same user ids from an external authentication service: In app1/models.py: class App1User(models.Model): user_id = models.UUIDField(unique=True) app1_field = models.BooleanField() In app2/models.py: class App2User(models.Model): user_id = models.UUIDField(unique=True) app2_field = models.BooleanField() I would like to have a combined viewset that can make it seem like these two are a single model with a list response as follows: [ { 'user_id': ..., 'app1_field': ..., 'app2_field': ... }, ... ] If I create or update with this viewset, it should save the data to each of the two models. -
Sentry: rate limit errors sent to prevent depletion of error quota
When an infrastructure incident happens, the application will start to generate thousands of occurrences of the same error. Is it possible to configure some kind of rate limiting or anything like that on the sentry client (or server) to avoid depleting the error quota? I'm using Python, Django and Celery mostly. -
PDF generation from an existing PDF using python/django
im using Django api, the user will upload an invoice im converting it to html using PDF.js and the user will label the invoice number, the buyer name, the buyer address then i will take a json response to generate 100 pdfs from the pdf that the user uploaded after i modified the values i got in the json response with the faker library in python. i made the task work but only with pdf 1.3 the code i used for pdf1.3 the Object of a PDF 1.3 7 0 obj << /Length 676 >> stream 2 J BT 0 0 0 rg /F1 0027 Tf 57.3750 722.2800 Td ( Simple PDF File 2 ) Tj ET BT /F1 0010 Tf 69.2500 688.6080 Td ( ...continued from page 1. Yet more text. And more text. And more text. ) Tj ET BT /F1 0010 Tf 69.2500 676.6560 Td ( And more text. And more text. And more text. And more text. And more ) Tj ET BT /F1 0010 Tf 69.2500 664.7040 Td ( text. Oh, how boring typing this stuff. But not as boring as watching ) Tj ET BT /F1 0010 Tf 69.2500 652.7520 Td ( paint dry. … -
AJAX code doesnt working with Django project
enter code hereIm making sort of a game where users can create or join a room with code and play a game...For now i only want to show all the users that are in the one room and i dont want the page to refresh when someone new enters. I asked few guys on reddit and they said i should use AJAX so i watched some tutorials but it doesn show anything. here is my code: views.py from asyncio.windows_events import NULL from hashlib import new from django.shortcuts import render, redirect from .models import Room, User from django.contrib import messages from random import randint from django.http import JsonResponse def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) def index(request): return render(request, 'index.html') def checkroom(request): if request.method == "POST": Uspeo = False username = '' code = 0 # join with code if 'dugme1' in request.POST: username = request.POST["username"] no1 = request.POST["no1"] no2 = request.POST["no2"] no3 = request.POST["no3"] no4 = request.POST["no4"] no5 = request.POST["no5"] no6 = request.POST["no6"] number = no1+no2+no3+no4+no5+no6 if len(username) == 0: messages.info(request, 'Enter your name!') return redirect('/') else: if Room.objects.filter(Room_code=number).exists(): user = User.objects.create(username=username, code=number) user.save() return redirect('/room/?code=' + number + '&username=' + username) else: messages.info(request, 'Code not … -
Django customized authentication Session bug
I'm working on a Django project using a customized authentication build by me, I run into a problem where users can bypass my login and get into the home page by simply typing the URL like this: "127.0.0.1/account/Adam" , "127.0.0.1/account/Bob" , "127.0.0.1/account/Alice" , those people are not registered in the database and yet they receive "welcome Adam", "welcome Bob", "Welcome Alice" I have been trying different methods from adding a global variable called Auth = False, and once a user is found in the database and the password is matched Auth will receive True, this kinda solved my problem but not as expected because once that variable becomes Auth = True example: if bob is registred in database and login has been successfully made, with same session Bob can type those urls and manipulating the last url parameter and get Welcome sam, Welcom Alfred.... from django.http import HttpResponse from django.contrib import messages from django.contrib.auth.models import auth from users.models import Composter from django.core.exceptions import ObjectDoesNotExist class MyView(): Vuser = None # Create your views here. def home(request): return render(request, 'users/home.html') #def compost_supplier_register(request): return render(request, 'users/compost_supplier_register.html') def composter_register(request): if request.method == 'POST': #extracting form data from a POST request and assigning it … -
How to use the address of the site inside the url tag django
I want to know if it is possible to use such an address?? {% url request.get_full_path page %} For example, pages like product list and search are on the same page and have separate links for the paginator -
FieldError at /store/submit_review/1/ Unsupported lookup 'id' for DateTimeField or join on the field not permitted
views.py def submit_review(request, product_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ReviewRating.objects.get( user__id = request.user.id, product__id=product_id) form = ReviewForm(request.POST, instance=reviews) form.save() messages.success(request, 'Thank you ! your review has been updated.') return redirect(url) except ReviewRating.DoesNotExist: form = ReviewForm(request.POST) if form.is_valid(): data = ReviewRating() data.subject = form.changed_data['subject'] data.rating = form.changed_data['rating'] data.review = form.changed_data['review'] data.ip = request.META.get('REMOTE_ADDR') #REMOTE_ADDR will stor the ip address data.product_id = product_id data.user_id = request.user.id data.save() messages.success(request, 'Thank you! Your review has been submitted.') return redirect(url) error I got: FieldError at /store/submit_review/1/ Unsupported lookup 'id' for DateTimeField or join on the field not permitted. Request Method: POST Request URL: http://127.0.0.1:8000/store/submit_review/1/ Django Version: 3.1 Exception Type: FieldError Exception Value: Unsupported lookup 'id' for DateTimeField or join on the field not permitted. -
How to use a relative path for Django FileStorage location in migrations?
I am defining a Model containing a FileField and cannot save the Files this FileField should contain in the media folder for unrelated reasons. Therefore I need to define a FileStorage that saves into a different Path. When defining said FileStorage in my model and passing it the DJANGO_ROOT variable from my django settings to build my location path, this gets resolved into a system specific path once I generate migrations for my models. Because the path is now specific to my development directories, I cannot apply the generated migration file on all of the production servers and generating migrations on all of the production servers is obviously not an option. I have also tried editing the path inside the auto generated migration itself, making it dependent on the django settings in there. Sadly, the manage.py migrate command tells me that it wants to generate new migrations for that model. How can I pass a relative path to my FileStorage location, allowing me to generate migrations for my production servers? My model: class ModelWithFile(models.Model): file = models.FileField( storage=FileSystemStorage(location=os.path.join(settings.DJANGO_ROOT, "folder_name"), verbose_name=_("FileObject"), ) Auto generated migration: from django.db import migrations, models from django.conf import settings import django.core.files.storage class Migration(migrations.Migration): dependencies = [ … -
django, path parameter in form don't work
My path looks like so: path('edit/<str:entry_name>/', views.edit, name='edit'). I want to access this path through a form like so: <form action="{% url 'edit' entry_name=entry_title %}" method="get"> {% csrf_token %} <input type="hidden" name="title" value="{{ entry_title }}"> <input type="hidden" name="content" value="{{ entry_content }}"> <input type="submit" value="Edit"> </form> But then I get this error: Reverse for 'edit' with keyword arguments '{'entry_name': ''}' not found. 1 pattern(s) tried: ['edit/(?P<entry_name>[^/]+)/\\Z']. It seems like entry_name is empty, but I use the entry_name parameter elsewhere on the page and it works fine. {% block title %} {{ entry_title }} {% endblock title %} is not empty, since I can see the titel on the tab-title. -
How to convert field values of a model into field names of a new one (model) in DJANGO 4?
I'm building models for a project in DJANGO 4, but I got stuck when it came to CONVERTING FIELD VALUES OF AN EXISTING MODEL INTO THE FIELD NAMES OF A NEW ONE (MODEL). As may be seen from the image I do attach, I have MODEL A with 'fieldName_3'. I'd appreciate a help to convert the values of this field into the field names of the MODEL B.Descriptive Image My advancing thanks! from django.db import models CHOICES = (('option1','option1'),('option2','option2')) class Model_A(models.Model): fieldName_1 = models.CharField(max_length=50) fieldName_2 = models.CharField(max_length=20) fieldName_3 = models.CharField(max_length=3) class Model_B(models.Model): def values_from_fildName3(): values = Model_A.fieldName_3 for value in values: value = models.CharField(max_length=4, choices=CHOICES) yield value With the code above I get the error "TypeError: 'DeferredAttribute' object is not iterable" -
Get form-data for Django tests
I would like to test a Django form, without spelling out myself all the POSTed data that would normally go into it. In a real application, this data would be provided by the browser, based on the form as rendered (as HTML) by Django. How do I get the data without going through the browser? form0 = MyForm(instance=obj) # form which would be shown in normal usage data = the_magic_function(form0) # data which would be posted if user just pressed submit right away # potentially manipulate some parts of this data to make the test interesting form1 = MyForm(instance=obj, data=data) # actual tests are on form1 -
Didnt print anything in response while using asnycio
So i use asnycio libruary to send response while task running in the backend but the response is being sent but display nothing in conole in backend. Here is my code: def http_call_sync(): for num in range(1, 6): sleep(1) print(num) r = httpx.get("https://httpbin.org/") print(r) async def async_view(request): loop = asyncio.get_event_loop() loop.create_task(http_call_async()) return HttpResponse('Non-blocking HTTP request') I need output like 1 2 3 4 5 in console -
Django Session across apps
request.COOKIES.get("myapp_sessionid") how above code line can be used to get session values across apps? I want to share session values across django apps in same django project. But session values get cleared in new second app. -
Django inline formset render by order
I Use Django 4.0.6 and Python 3.10. I have a Form with nested inline formset. The inline formset is orderable (can_order=True). The 'ORDER' value of the form will be set to an instance field "index". I use Javascript to order those forms in the template. When I submit the whole form and the form is not valid then the forms are not rendered by the 'ORDER'/'index' attribute. They will be rendered in the order they were created. To solve this I overwrite the __iter__ function of the formset to "Yield the forms in the order they should be rendered." (see django docs - BaseFormSet). My __iter__ function: def __iter__(self): """Yield the forms in the order they should be rendered.""" if self.is_bound: return iter(sorted(self.forms, key=lambda x: x.instance.index, reverse=False)) #return iter(sorted(self.forms, key=lambda x: x.cleaned_data['ORDER'], reverse=False)) else: return iter(self.forms) When I submit the form I get the following errors according to the values that I want to access (cleaned_data or instance). Error when accessing order through cleaned_data: FormXY has not attribute 'cleaned_data' Error when accessing index through instance: '<' not supported between instances of 'NoneType' and 'NoneType' I set a breakpoint in the __iter__ function to see whats the problem, but there is … -
How to feel test DB in Django with models with ManyToMnayFields?
I want to test speed of my project, so I need to feel my DB with test data. I have a model with lots of ManyToManyFields (later I will create more models): class Deciduous(PlantBasicCharacteristics): soil_type = models.ManyToManyField(SoilType) soil_moisture = models.ManyToManyField(SoilMoisture) soil_fertility = models.ManyToManyField(SoilFertility) soil_ph = models.ManyToManyField(SoilPh) And I am trying to create utility to feel DB with test data: from random import randint from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.db.models.fields import CharField, DecimalField from django.db.models.fields.related import ManyToManyField from django.shortcuts import get_object_or_404 from plants.models import Deciduous from plants.web_page_filter_fields import get_plant_class_fields PLANT_CLASSES = [Deciduous, ] TEST_DATA_AMOUNT = 3 class Command(BaseCommand): def handle(self, *args, **options): for plant_class in PLANT_CLASSES: fields_and_names = get_plant_class_fields(plant_class) data = [] for _ in range(TEST_DATA_AMOUNT): data.append(self.create_data(fields_and_names)) print(data) plant_class.objects.bulk_create([ plant_class(**values) for values in data ]) def create_data(self, fields_and_names): data = {} for field_name, field_model in fields_and_names.items(): if ('ptr' not in field_name and 'synonym' not in field_name and field_name != 'id'): if isinstance(field_model, CharField): data[field_name] = self.get_string_random() elif isinstance(field_model, DecimalField): data[field_name] = self.get_number_random() elif isinstance(field_model, ManyToManyField): data[field_name] = [self.get_choice_random(field_model)] return data def get_string_random(self): letters = [chr(randint(97, 122)) for _ in range(randint(5, 20))] return ''.join(letters).capitalize() def get_number_random(self): return randint(10, 15000) / 100 def get_choice_random(self, model): field_model = model.related_model field_choices … -
ImproperlyConfigured at /api/v1/auth/registration/account-email-verification-sent/
I'm getting this error after updating dj-rest-auth package to 3.0.0 from 1.1.0 main urls.py [![from allauth.account.views import confirm_email from dj_rest_auth.registration.views import VerifyEmailView from dj_rest_auth.views import PasswordResetConfirmView from django.urls import include, path, re_path][1]][1] path("api/v1/auth/", include("dj_rest_auth.urls")), path( "api/v1/auth/registration/", include("dj_rest_auth.registration.urls") ), path("api/v1/auth/registration/verify-email/", VerifyEmailView.as_view()), path( "api/v1/auth/password/reset/confirm/<slug:uidb64>/<slug:token>/", PasswordResetConfirmView.as_view(), name="password_reset_confirm", ), re_path( r"^api/v1/auth/accounts-rest/registration/account-confirm-email/(?P<key>.+)/$", confirm_email, name="account_confirm_email", ), -
How to insert count() value when using Django to develop Web front end
I'm developing a web visual board using Django. Here is the part of html that I want to insert database's values into. <tbody> {% for obj in data_list %} <tr> <th>{{ obj.id }}</th> <th>{{ obj.major }}</th> <th>{{ obj.name }}</th> <th>{{ obj.age }}</th> </tr> {% endfor %} </tbody> As you can see, this can help me to insert data: id, major, name and age. But now I want to insert values that use count() function in MySQL, which is fuzzy lookup: SELECT COUNT(Issue_date) AS NumberOfProducts FROM first_project.itsec_china WHERE Issue_date like '2022%'; Basically, I want to insert the number of those items issued in year 2022. How can I change my code, for example, this part: {{ obj.age }} I'm trying to find someone have the knowledge to give me the answer or a place to study about it. Thank you in advance. -
Django Rest Framework Testing
I have a LoginSerializer that has the block of code as below def validate(self, attrs): username = attrs.get('username', '') password = attrs.get('password', '') user = auth.authenticate(username=username, password=password) if user: if user.is_active is False: raise AuthenticationFailed( 'Account is disabled, contact admin') if not user.is_verified: raise AuthenticationFailed('Email is not verified') return { 'username': user.username, 'firstname': user.firstname, 'lastname': user.lastname, 'role': user.role, 'tokens': user.tokens } else: raise AuthenticationFailed('Invalid credentials, try again') and a test case as below; class UserLoginTest(BaseTest): def test_inactive_user_can_login(self): self.client.post( self.register_public, data=valid_user, format='json') user = User.objects.get(username=valid_user['username']) user.is_verified = True user.is_active = False user.save() response = self.client.post( self.login_url, valid_login_user, format='json') print(response.data) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) When I run the test with is_active = False I get Invalid credentials, try again. Why is it that when is_active=False the user is not found even though the user is there? Same with when I try to login from swagger. -
Why is VS Code loading all my previous logs when I run docker-compose up for django rest framework?
I run docker-compose up I don't know why but all the previous logs that took alot of time, generate again. which is why it takes 5 minutes for the server to be up and running. To avoid that previously I used to quit the server, clear the window, remove the terminal and added new terminal and it solved the problem and started the server from fresh. but now it is not working too. kindly help I am new to django and docker. -
Bootstrap striped table format lost when updating table with fetch
I am using Django and I have a table which is formatted using bootstrap. The class is class="table table-striped". The table initially looks good. It has a delete button which allows users to delete a row. When clicked the data is deleted from the Django model and the table rows are removed and repopulated using fetch. Everything works well but the striped formatting is lost. The bootstrap formatting is still working to some degree and the table is the same size/shape but the background colour of alternating striped rows is lost. I've tried removing and re-adding the class with the javascript but it doesn't work. Any suggestions would be great. HTML {% if pairs %} <table class="table table-striped" id="pairs_table"> <thead> <tr> <th scope="col">Primer</th> <th scope="col">Product(bp)</th> <th scope="col"></th> </tr> </thead> <tbody> {% for pair in pairs %} <tr> {% if pair.forward.pk == primer.pk %} <td> <a href="{% url 'primer' pair.reverse.id %}">{{ pair.reverse }}</a> </td> <td>{{ pair.product }}</td> <td id="delete_pairing"> <button type="button" class="btn btn-warning" onclick="delete_pair('{{primer.id}}','{{pair.reverse.id}}')"><i class="bi bi-trash3"></i></button> </td> {% else %} <td> <a href="{% url 'primer' pair.forward.id %}">{{ pair.forward }}</a> </td> <td>{{ pair.product }}</td> <td id="delete_pairing"> <button type="button" class="btn btn-warning" onclick="delete_pair('{{primer.id}}','{{pair.forward.id}}')"><i class="bi bi-trash3"></i></button> </td> {% endif %} </tr> {% endfor %} JAVASCRIPT …