Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python step debugger breaking upon introducing asyncio and httpx
Python step debugger breaking upon introducing asyncio and httpx. Developing Django application using vscode using this debug configuration { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true } ] } Nothing changed other than introducing this asynchronous module. I can also fix the debugger by removing import of httpx and asyncio. A viable workaround for me would be any way to send a http request without awaiting the response, but using asyncio and httpx seems to be a common approach to do this. -
How to dynamically add a constraint to a model from a field class in Django?
I've created a ChoiceField to be used as a replacement for models.CharField with which I would like to dynamically add a constraint to the model. class ChoiceField(models.CharField): def __init__(self, *args, **kwargs): model = apps.get_model(app_label='user', model_name='TestModel') constraint = models.CheckConstraint( name=f"{model.app_label}s_{model.model_name}s_test_test_valid", check=models.Q(f"test_choice__in={self.choices}") ) model._meta.constraints.append(constraint) or class ChoiceField(models.CharField): def contribute_to_class(self, cls, name, private_only=False): super().contribute_to_class(cls, name, private_only) constraint = models.CheckConstraint( name=f"{cls._meta.app_label}s_{cls._meta.model_name}s_{name}_valid", check=models.Q(f"{name}__in={self.choices}") ) cls._meta.constraints.append(constraint) and I then initialize the field with: ChoiceField(model_name="TestModel")... However, this approach doesn't work because apps are not loaded yet. Is there another alternative approach that I'm not seeing? -
No module named 'distutils.command.bdist_msi' when installing celery[sqs]
I have Django app with celery task. I am switchI am trying to install celery[sqs] as written in documentation however I cannot because I am getting error during instalation. I want to use Amazon SQS on AWS in my Django app and I am not sure how to do it without celery[sqs] package installed. I know that I can use Amazon MQ instead but I am running few task a day and SQS would be more than enough for me and less expensive. Do you know how to fix this issue? Collecting pycurl~=7.44.1 Using cached pycurl-7.44.1.tar.gz (227 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\user\AppData\Local\Temp\pip-install-qt57cr38\pycurl_3d30f8432e6a4a298adece529a63bace\setup.py", line 938, in <module> setup_args['cmdclass'] = {'bdist_msi': get_bdist_msi_version_hack()} File "C:\Users\user\AppData\Local\Temp\pip-install-qt57cr38\pycurl_3d30f8432e6a4a298adece529a63bace\setup.py", line 580, in get_bdist_msi_version_hack from distutils.command.bdist_msi import bdist_msi ModuleNotFoundError: No module named 'distutils.command.bdist_msi' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed -
Is it possible to make dynamic permission management of a group per view?
For example I have a view called Article and I have groups called Author and Reader. And I want to o set to the author permissions to get and post to the Article view, and set permission only get to the Reader group. Also I want to add or remove any permission from any group to any Views from Django dashboard. I have already seen Django group permissions for the dashboard only, but I want to extent this feature to any view independently if the view is a rest view or MVC view. -
Setting 2 columns as primary key OR using many to many in django models
I am creating a django model and I have a table that is to do with accounts having planned parking spaces (So many accounts can have many planned parking spaces and many parking space can have many accounts). The table looks like a Many - to - Many table. class AccountsPlannedParkingSpaces(models.Model): AccountId = models.ForeignKey('Account',on_delete=models.CASCADE,null=False,blank=False) ParkingSpaceId = models.ForeignKey('ParkingSpace', on_delete=models.CASCADE,null=False,blank=False) PlannedDateTime = models.DateTimeField(blank=False, null=False) This is the code. But obviously AccountId and ParkingSpaceId have to be a Composite primary key in django. My question is should I just put a many to many field called parking spaces in Account and allow django to create a intermediary table itself or should I still define this table and go through the trouble of having to find a way to have a Composite primary key in django? Also how can I make this a composite primary key in django? -
How to create logout function django rest framework
I am using django rest framework. and rest_framework.authentication.TokenAuthentication And I have a account model: class Account(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = MyAccountManager() def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True I try to create a logout function: class LogoutView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): user = request.user Token.objects.filter(user=user).delete() return Response({"detail": "Logged out successfully."}, status=status.HTTP_200_OK) And I am using swagger for the api data. But when I am logged in and I execute the lgout function in swagger. I see the message: { "detail": "Logged out successfully." } But in fact I am nog logged out. Because when I look in the django admin panel I still see the existing token. And also I can return the user data in swagger. Question: how to create logout function that will delete the token? -
showing data on graph in django
I am new to Django, I want that user should be able to see total user registered on graph showing progress on the basis of months view.py def dashboard(request): title = 'Dashboard' request_url = request.get_full_path() username = request.user.username local_datetime = datetime.now() today = date.today() start_of_month = today.replace(day=1) end_of_month = start_of_month + relativedelta(day=31) monthly_data = ( Clinic.objects .filter(updated__range=(start_of_month, end_of_month)) .annotate(month=TruncMonth('updated')) .values('month') .annotate(count=Count('register_clinic_user_id')) .order_by('month') ) labels = [data['month'].strftime('%B %Y') for data in monthly_data] values = [data['count'] for data in monthly_data] clinic_list = Clinic.objects.all() content = { 'title': title, 'requesturl': request_url, 'clinic_list':clinic_list, 'username':username, 'current_datetime':local_datetime, 'graph_data':values, } return render(request, 'admin/dashboard.html', content) graph.js new Chart(ctx2, { type: "line", data: { labels: ["Jan","Feb","Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], datasets: [{ label: "Mobile apps", tension: 0.4, borderWidth: 0, pointRadius: 0, borderColor: "#16b385", borderWidth: 3, backgroundColor: gradientStroke1, fill: true, data: {{graph_data}}, maxBarThickness: 6 }, ], }, error - syntax error when i write {{graph_data}} please let me know the accurate way to show this data on graph thanks in advance -
How to fix Django's incorrect redirection when prefix_default_language=False?
Django - Multi-language does not redirect correctly when prefix_default_language=False. 404 page displayed when changing language (but when changing second language page displayed correctly). In my settings.py LANGUAGE_CODE = 'uz' enter image description here enter image description here enter image description here -
Django Find parent by two children
class Company(models.Model): title = models.CharField() class Office(models.Model): сompany = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField() class Human(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) office = models.ManyToManyField(Office) how to find current user's company without using Prefetch. Because it's expensive -
Django ORM : Filter to get the users whose birthday week is in n days
I am trying to make a django query which is supposed to gave me the users whose birthday week is in n days. I already tried to use the __week operator but it's not working as expected : now = timezone.now().date() first_day_of_next_week = (now + timedelta(days=(7 - now.weekday()))) if now + relativedelta(days=n_days) == first_day_of_next_week: return qs.filter(birth_date__isnull=False, birth_date__week=first_day_of_next_week.strftime("%V")) Indeed, for example if a user is born the 24/06/1997, the 24/06 is not on the same week nbr in 1997 than in 2023, so it's giving me unexpected results. Could you help me on this ? -
Is there a solution for changing the default installation successful and showing the required page in django? [closed]
Even after trying multiple times the django basic webapp to show hello world is not coming instead every attempt resulted in th following image.the case is same even after following instructions of django site. i wanted to get hello world written django page but getting only installation successpage -
FastTenantTestCase : Exception: Can't create tenant outside the public schema. Current schema is fast_test #938
Trying to run test cases using FastTenantTestCase, following are the package versions: django - 3.2.16 django-tenants - 3.3.4 Sample code: from django_tenants.test.cases import FastTenantTestCase class TestWorkflowDocumentCategories(FastTenantTestCase): """ class to test workflow document categories """ def setUp(self) -> None: self.client = TenantClient(self.tenant) self.url = reverse('sample-url-list') self.existing_document_categories = {'xyz'} self.factory = SampleFactory() def test_document_categories_list(self) -> None: response = self.client.get(self.url, {}, **self.header) self.assertEqual(response.status_code, status.HTTP_200_OK) ERROR: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django_tenants/test/cases.py", line 134, in setup_test_tenant_and_domain cls.tenant.save(verbosity=cls.get_verbosity()) File "/usr/local/lib/python3.9/site-packages/django_tenants/models.py", line 100, in save raise Exception("Can't create tenant outside the public schema. " Exception: Can't create tenant outside the public schema. Current schema is fast_test. Can anyone suggest solution to solve this issue? we tried to over ride setUpClass method but still isn't resolved -
update multiple fields in djnago
I have Inventory and Product Classes in models - The Product class have Inventory.item as ManyToManyField I can select items and save them in Product.items from Inventory.item. I try to get quantity from request.POST.getlist() and submit request when I submit the request I want the Inventory.quantity to by subtract automatically whatever gets values as list from request.POST.getlist() after subtract Inventory.quantity model will update the items quantity by update this my codes. I am not sure if I make correctly update I still get AttributeError: 'list' object has no attribute 'split' models.py class Inventory(models.Model): stock_transaction_numbers = models.PositiveBigIntegerField(null=True, blank=True, unique=True,) item = models.CharField(max_length=700,null=True, blank=True) unit = models.CharField(max_length=100,null=True, blank=True) quantity = models.IntegerField(null=True, default=0, blank=True) class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True, verbose_name="name") items = models.ManyToManyField(Inventory, blank=True,verbose_name="items - ManyToManyField" ) in Views.py def get_order(request, pk): product = get_object_or_404(Product, pk=pk) inventory = Inventory.objects.filter(id__in=product.items.all()) inventory_id = Inventory.objects.filter(id__in=inventory).values_list('id', flat=True) get_quantity = Inventory.objects.filter(id__in=inventory_id).values_list('quantity', flat=True) quantity = request.POST.getlist('quantity') subtract_quantity = ([get_quantity - quantity for quantity, get_quantity in zip(quantity, get_quantity)]) for i in inventory_id: Inventory.objects.filter(id__in=inventory_id).values_list('id', flat=True) for x in subtract_quantity: Inventory.objects.filter(id__in=inventory_id).update(quantity=F (subtract_quantity) + 1) I got 'int' object has no attribute 'split' unhashable type: 'list' any help would be greatly appreciated -
How use Django's ORM for read and write operations from the secondary DB who's models are not present in the project?
Here is the current scenario, I have 2 databases in the project DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB1', 'USER': 'DB1_ADMIN', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': 5432, 'ATOMIC_REQUESTS': True, }, 'crm': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB2', 'USER': 'DB2_ADMIN', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': 5432, 'ATOMIC_REQUESTS': True, }, } I can use the django's ORM for the DB1 because it the primary DB of this project, but the DB2 is the database of another project hence the tables that are in the DB2 are not reflected by models in current project. I'm able to read and write data from the DB2 using the raw queries just like below rfp_query = f"""SELECT id, currency, estimated_budget, reconciled_budget, savings, total_items FROM accounting_rfpbudget WHERE rfp_id = {rfp_id} """ cursor = connections['crm'].cursor() cursor.execute(rfp_query) but I want to use the django's ORM as it takes a lot of effort and time to manage all the stuff on my own, please let me know is there any way to use django's ORM for DB2 remember there are no models in project that are associated with the database tables. -
PEP8 between specific lines
I have some huge files in my codebase which have many pep8 related issues. Is there any way to analyze specific lines with pep8 pep8 input /path/to/my-code.py --lines=100-200 So that I can analyze specific part of the code? -
How do I fix the error 'EmailAuthBackend' object has no attribute 'authenticate' when using Facebook login in Django?
I am learning Django using the book Django 4 by Example by Antonio Mele where I was developing social website referencing the book. I want to social authenticate using facebook I followed the procedures as per the book created developers account in facebook set up facebook login app. When I try to login using facebook the bellow error is coming: Traceback (most recent call last): File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in call return self.application(environ, start_response) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\core\handlers\wsgi.py", line 124, in call response = self.get_response(request) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\core\handlers\base.py", line 140, in get_response response = self._middleware_chain(request) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner response = response_for_exception(request, exc) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception response = handle_uncaught_exception( File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\core\handlers\exception.py", line 181, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django_extensions\management\technical_response.py", line 40, in null_technical_500_response raise exc_value.with_traceback(tb) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\views\decorators\cache.py", line 62, in wrapper_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\social_django\utils.py", line 46, in wrapper return func(request, backend, *args, **kwargs) File "C:\Users\Bibek Rawat\PycharmProjects\bookmarks\venv\lib\site-packages\social_django\views.py", line 30, in complete return do_complete( … -
I need to add one model to another model in Flutter
I'm really confused on how do I add director model to my show model. I'm writing Android application in Flutter, that uses local Django Rest API. This is Shows model import 'package:flutter/widgets.dart'; import 'package:kulises_app/models/directors.dart'; class ShowsModel with ChangeNotifier { final int id; final String name; final String annotation; final String language; DirectorModel? director; final String image; ShowsModel( {required this.id, required this.name, required this.annotation, required this.director, required this.language, required this.image} ); factory ShowsModel.fromJson(dynamic json) { return ShowsModel( id: json['id'], name: json['name'] as String, annotation: json['annotation'] as String, language: json['language'] as String, image: json['image'] as String, director: json['director'] !=null ? DirectorModel.fromJson(json['director']) : null; ); } static List<ShowsModel> showsFromSnapshot(List snapshot) { return snapshot.map((data) { return ShowsModel.fromJson(data); }).toList(); } } This is Director Model import 'package:flutter/widgets.dart'; class DirectorModel with ChangeNotifier { final int id; final String name; final String surname; final String image; DirectorModel({required this.id, required this.name, required this.surname, required this.image}); factory DirectorModel.fromJson(dynamic json) { return DirectorModel( id: json['id'], name: json['name'] as String, surname: json['surname'] as String, image: json['image'] as String, ); } static List<DirectorModel> directorFromSnapshot(List snapshot) { return snapshot.map((data) { return DirectorModel.fromJson(data); }).toList(); } } So the error is on this line director: json['director'] !=null ? DirectorModel.fromJson(json['director']) : null; It expects to find … -
Validation of the serial number against the mask in Django rest
There are two tables - equipment type and equipment, the type has a line with a serial number mask, the equipment has a line with a serial number. When creating new equipment, validation must go through, that is, the string with the serial number is compared with each mask of the equipment type, and if a match is found, the equipment is tied to the type, the question is, how is it better to implement this on the django rest framework? The check is carried out according to the principle: N is a number from 0 to 9; A is a capital letter of the Latin alphabet; a is a lowercase letter of the Latin alphabet; X is a capital letter of the Latin alphabet or a number from 0 to 9; Z is a character from the list: “-“, “_”, “@” That is, if the equipment has a serial number of 0QWER9@123, it corresponds to a mask with characters like NAAAAXZXXX models.py from django.db import models from django.core.validators import MinLengthValidator from django.core.validators import RegexValidator class Type_Of_Equipment(models.Model): name = models.CharField(verbose_name='Тип оборудования', max_length=64, blank=True, default='Без названия') sn_mask = models.CharField(verbose_name='Маска серийного номера', blank=False, max_length=10, validators=[MinLengthValidator(10), RegexValidator(regex=r'^[NAaXZ]+$', message='Использованы недопустимые символы')]) class Equipment(models.Model): code … -
How can I submit Django forms without losing previously rendered HTML?
I am new to Django framework. I am trying to create a mini-project where my UI will have 3 html forms. The intended workflow is that I will submit a text in Input String field. Then I will submit some substrings of the above submitted string and increase the score. The problem I am having is when I submit the substring my page reloads and it resets the previously rendered html. Hence, I lose my actual string for which I am submitting substrings. The html code for Forms <div style="padding: 20px;"> <h1>Words Starting with consonants</h1> <form id="form2" action="consonant_submit/" method="post"> {% csrf_token %} <label for="Stuart">Stuart Text:</label> <input type="text" id="stuart" name="stuart"> <br> <label for="2">Stuart Score:</label> <input type="text" id="score1" name="score1"> <br> <input type="submit" value="Submit stuart"> </form> </div> <div style="padding: 20px;"> <h1>Words Starting with consonants</h1> <form id="form3" action="vowel_submit/" method="post"> {% csrf_token %} <label for="kevin">Kevin Text:</label> <input type="text" id="kevin" name="kevin"> <br> <label for="2">Kevin Score:</label> <input type="text" id="score2" name="score2"> <br> <input type="submit" value="Submit kevin"> </form> </div> The consonant_submit & are django view functions. I am attaching my sample urls.py and sample views.py Urls.py from django.urls import path from . import views urlpatterns = [ path("",views.index,name="index"), path('consonant_submit/', views.consonant_submit, name='consonant_submit'), path('vowel_submit/', views.vowel_submit, name='vowel_submit'), ] And views.py from django.shortcuts … -
python - How to update multiple dictionary key-value without using for loop
I have a list of dictionaries with the same keys but different values. Example: [{ Price = 100; Quantity = 3; }, { Price = 200; Quantity = 5; }] Is there a way to update the value of a particular key in all dictionaries in one go without using for loop? That is, is there a way to make Quantity=0 for all dictionaries in the list in one go? I am looking for performance since I have a huge list of dictionaries, and I'm under the assumption that there may be a faster way to do this than using a for loop. I have. gone through multiple questions on stack overflow but did not get any satisfactory response. -
send selected date to django using htmx & pickadate.js
I use the pickadate.js widget, to select a date. The selected date should be sent to django do query availability. pickadate.js creates a hidden input field with name="date_submit". I use jQuery to add some htmx attributes to listen on the change event of that element. That works so far and the hidden input element has all the necessary hx-attributes assigned to it. I debugged the events with htmx.logAll();. the 'change' event is fired on the element. However, the hx-attributes on the hidden input field don't have any effect and no requests are made to the django backend. The code is part of a form, placed in a modal. rendered hidden input field: <input type="hidden" name="date_submit" value="2023-05-26" hx-trigger="change" hx-get="/" hx-target="#test"> Date Formfield: <div class="form-floating"> {% render_field reservation_form.date class="datepicker form-control mb-3" %} <label for="{{ reservation_form.date.id_for_label }}">Event Date</label> </div> Script: <script> htmx.logAll(); var $input = $('.datepicker').pickadate({ format: 'yyyy-mm-dd', formatSubmit: 'yyyy-mm-dd', min: 0, max: 90, disable: {{ blocked_dates }}, firstDay: 1, onOpen: function() { // Get the hidden input field var hiddenInput = $(this.$node).siblings('[name="date_submit"]'); // Add HTMX attributes to the hidden input field hiddenInput.attr('hx-trigger', 'change'); hiddenInput.attr('hx-get', "{% url 'home' %}"); hiddenInput.attr('hx-target', '#test'); } }); $input.on('change', function() var hiddenInput = $(this).siblings('[name="date_submit"]'); hiddenInput.val($(this).val()); htmx.trigger(hiddenInput[0], 'change'); }); … -
How can I use keyple API to emulate a badge for accessing university buildings with NFC-enabled smartphones?
I'm working on a project which purpose is to emulate a badge using calypso protocol on a smartphone (with an NFC chip) via website (eg django) or an android application in order to access university buildings without the badge but only with the phone. I'm looking for some information on internet and I discovered that there are keyple api but I'm not sure if it works for my job. The question is: keyple api are ok for my aim? If so, it's better to develop a website or an android app? -
Auto start Nginx and Gunicorn in Docker
I am a student, and I am currently trying to deploy my Django application on Docker Ubuntu using Nginx and Gunicorn. However, when I restart the container, both Nginx and Gunicorn are also turned off. I have to use the command "docker attach " to enter the container and run the commands service nginx start and systemctl start gunicorn. Is there any way to automatically start Nginx and Gunicorn when the container is restarted? Thank you sincerely. [This is the configuration file.](https://i.stack.imgur.com/HC7Ol.png) I have tried writing a start.sh file like this: #!/bin/bash # Start Nginx service nginx start # Start Gunicorn systemctl start gunicorn exec "$@" and Dockerfile FROM my_image COPY start.sh /start.sh RUN chmod +x /start.sh EXPOSE 80 CMD ["/start.sh"] -
The best technology for chat in django, Django-channels, FastAPI, FlaskSockerIO, Tornado and others [closed]
I want to create a chat in my django app. Which technology should I choose? Many people write that django-channels is bad, so I would like to know your opinion Sorry if this question was asked, but unfortunately I didn't find it -
Select element options not opening on first click with Bootstrap
I have a html template with four selects. The same thing happens to me in all four. When I click on the select the first time it doesn't open, but after that, the following times it does. I want the options to be open the first time too. Los selects son así: <div class="input-group"> <select class="selectpicker" multiple data-live-search="true" id="src" name="src"> {% for value, label in jobs%} <option value="{{ value }}">{{ label }}</option> {% endfor %} </select> </div> The javaScript part is this. I have tried to do it in many ways but I can't. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script> <script> // Wait for the DOM to be ready document.addEventListener("DOMContentLoaded", function() { // Select all <select> elements var selectElements = document.querySelectorAll("select"); // Apply the Bootstrap Select plugin to each <select> element selectElements.forEach(function(selectElement) { console.log("DOM ready"); new bootstrap.Select(selectElement); }); }); </script>