Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail Django ValidationError ['“8bf95516-2a6d-494d-817d-e931ab7df570” is not a valid UUID.']
I activated wagtail's localization support. Since then this error raises randomly. The Django App is running within Apache mod_wsgi in a virtualenv. To solve it, I tried: Searching and removing the mentioned UUID from database But another UUID will throw the same exception Disable wagtail-metadata, since this app always was on top of the stackdump no effect Because of randomness I tried to find some cache mechanism I failed So, please help me :-) Environment: Request Method: GET Request URL: https://*********************** Django Version: 3.1.12 Python Version: 3.8.5 Installed Applications: ['home', 'blog', 'shop', 'search', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.postgres_search', 'wagtail.contrib.search_promotions', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'wagtail.contrib.modeladmin', 'wagtail.contrib.settings', 'wagtail.api.v2', 'wagtail_localize', 'wagtail_localize.locales', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sitemaps', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'salesman.core', 'salesman.basket', 'salesman.checkout', 'salesman.orders', 'salesman.admin', 'rest_framework', 'wagtailmenus', 'wagtailthemes', 'wagtail.contrib.routable_page', 'cookielaw', 'analytical', 'wagalytics', 'wagtailfontawesome', 'allauth', 'allauth.account', 'allauth.socialaccount'] Installed Middleware: ['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', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.legacy.sitemiddleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', 'wagtailthemes.middleware.ThemeMiddleware', 'django.middleware.locale.LocaleMiddleware'] Traceback (most recent call last): File "/opt/cms/.virtualenvs/wagtail/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2336, in to_python return uuid.UUID(**{input_form: value}) File "/usr/lib/python3.8/uuid.py", line 166, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') During handling of the above exception ('UUID' object has no attribute 'replace'), another exception occurred: File "/opt/cms/.virtualenvs/wagtail/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File … -
'Request' object has no 'accepted_renderer', djangorestframework-datatables
In my project, I wish to use djangorestframework-datatables to automatically paginate my jquery datatables. However, I have faced this error: "'Request' object has no 'accepted_renderer'. Here are the relevant codes: (Serializer, ViewSet, javascript) class MedicationStoreSerializer(serializers.ModelSerializer): container_photo = Base64ImageField() medicine_photo = Base64ImageField() class Meta: model = MedicationStore fields = ['senior_id', ...] ---------------------------------------------- class MedicationStoreViewSet(viewsets.ModelViewSet): queryset = MedicationStore.objects.all() serializer_class = MedicationStoreSerializer ---------------------------------------------- var gSeniorTb = $('#senior_participation_tb').DataTable({ "serverSide": true, "ajax": $ajax_summary_url, "columns": [ { "data": "id"}, ..., ] }) I've tried installing pyyaml from another question, it did not work. I have these basic REST framework settings: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_datatables.renderers.DatatablesRenderer', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_datatables.filters.DatatablesFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination', 'PAGE_SIZE': 25, } -
django autocomplete light search not populating values
I am using django autocomplete light search for making searchable dropdown in my application but it is not populating values views.py from dal import autocomplete from .models import States class StatesAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = States.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs models.py class States(models.Model): name = models.CharField(max_length=200) modified_by = models.DateTimeField(auto_now=True) def __str(self): return self.name forms.py class RetailerForm(forms.ModelForm): name = forms.CharField(max_length=1000, required=True, error_messages={ 'required': 'Name is mandatory', 'max_length': ' Name cannot exceed 1000 characters' }, label='Name', widget=forms.TextInput(attrs={'class': 'form-control'})) state = forms.ModelChoiceField( queryset=States.objects.all(), widget=autocomplete.ModelSelect2( url='states_autocomplete', attrs={'class': 'form-control'}), label='State' ) urls.py from retail.views import StatesAutocomplete urlpatterns = [ path('states-autocomplete/', StatesAutocomplete.as_view(), name='states_autocomplete' ] Not sure why StatesAutocomplete is not working and populating values. -
Django DetailView pk error: can't match the last one
My new to django. I am creating a simple model for my to do app in django. Here, I have used DetailView to get the details and using the int "pk". When I'm running my server the /task/1/ is working fine but when I'm running task/2/ to check the other task it is shwoing this error: error My views.py: views.py My app urls.py: urls.py template of detailview See, when I'm running task/1/ there's no error: task/1/ -
HTML tags in string are getting printed in web page
I am using Elasticsearch highlighting which returns string with highlighted text between html tags e.g. { field: "\<b> highlighted text \</b>" } Now I need to print this on web page using django , the <b></b> tags are also getting printed in the web page. Sample code snippet for html page is like this <body> {% for result in results %} <div> Result : {{ result.field }} </div> {% endfor%} </body> I want the highlighted text to be printed in bold , but the tags are getting printed instead. -
Django hosting static files in AWS S3 causing CORS error when trying to access admin font files
I setup Django to store all static files on S3 and with the "collectstatic" command, all the admin files where copied and when I visit the admin site the CSS and JS files are sourced from the S3 bucket correctly. For example: https://bucket.s3.amazonaws.com/static/admin/css/base.css https://bucket.s3.amazonaws.com/static/admin/js/vendor/jquery/jquery.js But when it tries to access the Font files .woff I get the following error: Access to font at 'https://bucket.s3.amazonaws.com/static/admin/fonts/Roboto-Light-webfont.woff' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. It's weird that it gives me access to all the files except the font files: -
How to delete selected Cart Item using Django rest framework?
I'm using Django as backend, PostgresSQL as DB and HTML, CSS and Javascript as frontend I'm calling Django API with the help of Javascript to show the cart item to authenticated user serializer.py from .models import * from rest_framework import serializers class productserializers(serializers.ModelSerializer): class Meta: model = Cart fields = '__all__' depth = 1 views.py @api_view(['GET']) def showproduct(request): if request.method == 'GET': result = Cart.objects.filter(user = request.user) serialize = productserializers(result, many = True) return Response(serialize.data) main.js $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/showdata', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr><td style="font-style:bold">' +data[i].product.name+'</td><td style="font-style:bold">' +data[i].product.price+'</td><td><a href=' +data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><a href='#'><button type="button" class="btn btn-outline-danger">DELETE</button></a></td></tr>'); $("#tableProduct").append(row); } } }); }); Well, from above code on main.js ... <td><a href='#'><button type="button" class="btn btn-outline-danger">DELETE</button></a></td> ... In this line I want to implement delete function. Where user can delete the selected item from cart. So, How to implement delete function that can delete the item from cart and show the response in Template. -
Aplhanumeric range between 2 input values
Hi guys i need help with generating field values between alphanumeric input in javascript. i have 2 input fields UIV = with range (C0, C1, C2, C3, C4, C5, C6, C7, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, T1, T2, T3, T4, T5, S1, S2) LIV = with range (C0, C1, C2, C3, C4, C5, C6, C7, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, T1, T2, T3, T4, T5, S1, S2) vertebra = the range between UIV and LIV i want to be able get the values between for example vertebra= C0, C1, C2, C3 if UIV = C0 LIV= C3 or vertibra = C0, C1 if UIV = C0 and LIV=C1 I need help using javascript or python -
Passing a String from an HTML input to a python script back out to the webpage using Django
Ok! I'm a noob to Django so please forgive me. I am trying to learn django and I am attempting to pass a string from an input in my html frontend to a python file/function which contacts google api and then I would like that information spit out back onto the webpage. Right now I can't figure out how to get the function to work. Or, Idk what I'm doing wrong. Here is my views file from templates.pyfile.pyapi import Api from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Tube from templates.pyfile import pyapi # Create your views here. def tubeView(request): search = Tube.objects.all() return render(request, 'home.html') def search(request): kw_list = request.POST['content'] new_search = Tube(content=kw_list) new_search.save() print(kw_list) reApi().main(kw_list) return HttpResponseRedirect('home/') Here is my python file from googleapiclient.discovery import build from pytrends.request import TrendReq import matplotlib.pyplot as plt import pandas as pad import time pytrends = TrendReq() class Api(): def main(x): self.searchAPI(c) def searchAPI(self, kw_list): pytrends.build_payload(kw_list, cat=0, timeframe='today 1-m', geo=country_var, gprop='youtube') data = pytrends.interest_over_time() mean = data.mean() print(mean) plt.plot(data) plt.savefig('Plotzz.png') plt.legend(kw_list, loc='upper left') I'm new so please be easy but can anyone help guide me in the right direction? I've been reading all day and cant figure it out. … -
Testing with RequestFactory seems to pass for non existing route
I'm trying to verify if accessing routes of my Django application would return a 200 status code. As I was writing repetitive test code, I search for some options and found that I could use RequestFactory with a mixin. But what I'm not understanding is why the test is not failing for a non existing route. I have a class-based view called IndexView which I'm trying to test, but the idea is to use the mixin to test others as well. The tests below will consider a non existing route called i-dont-exist: Using client What I see here is that I'm not using an instance of my view inside the test yet, but only the get to i-dont-exist route. from django.test import TestCase, RequestFactory from .. import views class ExampleViewTest(TestCase): def test_if_route_exists(self): response = self.client.get('/i-dont-exist') status_code = response.status_code self.assertEqual(status_code, 200) Running python3 manage.py test: ====================================================================== FAIL: test_if_route_exists (page.tests.test_views.ExampleViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "xxxxx/page/tests/test_views.py", line 15, in test_if_route_exists self.assertEqual(status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.014s FAILED (failures=1) Using RequestContext Now I'm using my class-based view inside the test. class ViewMixinTest(TestCase): def setUp(self): # Every test needs access to the request factory. self.factory = … -
Create accounts and API tokens for live mode and test mode
I want to create a system that works similar to stripe. There'll be live API keys, as well as test API keys. I have been thinking of how to implement this architecture, and I am not sure the best way to go about it. I found a similar question on this but it didn't help much. Architecturing testmode/livemode using OAuth 2 token My current progress is basically: I have decided to use https://github.com/James1345/django-rest-knox instead of DRF's default authtoken because knox supports multiple token creation and I thougt I needed that feature. I intend to create tokens as pub_key_<token> and test_key_<token> and remove or strip the prefix before authentication I intend to create a LiveAccount Model and a TestAcoount model. However, after authenticating the request from a test api token, it's unclear how to route or perform requests to TestAcoount instead of LiveAccount. Please any ideas or a better implementation strategy is highly welcomed -
Writes id instead of name
I am new to Django, I have such a problem that Id is written instead of the category name, how can this be solved? Attached code, code not complete (only used part). I don't know how to do it anymore, most likely the problem is in views.py model.py class Category(models.Model): category_name = models.CharField(max_length=64, unique=True) subscribers = models.ManyToManyField(User, blank=True, null=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.category_name class Post(models.Model): PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE) PostNews = 'PN' PostArticle = 'PA' # «статья» или «новость» POSITIONS = [ (PostArticle, 'Статья'), (PostNews, 'Новость'), ] title = models.CharField(max_length=50) positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle) data = models.DateTimeField(auto_now_add=True) postCategory = models.ManyToManyField(Category, through='PostCategory') previewName = models.CharField(max_length=128) text = models.TextField() rating = models.SmallIntegerField(default=0) def like(self): self.rating +=1 self.save() def dislike(self): self.rating -=1 self.save() def preview(self): return self.text[0:124] + '...' def __str__(self): return self.title class Meta: verbose_name = 'Пост' verbose_name_plural = 'Посты' def get_absolute_url(self): return f'/news/{self.pk}' class PostCategory(models.Model): pcPost = models.ForeignKey(Post, on_delete=models.CASCADE) pcCategory = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: verbose_name = 'Пост категория' verbose_name_plural = 'Пост категории' def __str__(self): return f'{str(self.pcPost)}, имеет категорию {str(self.pcCategory)}' views.py I think the mistake is here class new(LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Post template_name = 'new_home.html' context_object_name = 'new' permission_required = … -
get distinct "title" in mysql in django
I have used django to develop a web app. I want to get the distinct "title" form the queryset get by filter. But I use mysql so could not pass "title" to distict. How could I filter the queryset with the distinct "title"? query_set = CourseInfo.objects.filter(discipline_id=id).distinct('title') return render(request, 'main.html', context={'query_set':query_set}) I get error for this in mysql as it may only used in postgresql ` -
When do we get https response 377?
I am using bunny CDN to redirect to my API endpoint and it worked initially for some time now it has been throwing http response 377. I have not found any explanatory answer for such https response. -
ListView can not return to other page. NameError
I have made ListView, it has "Try and Except block" When it passes try block, it shows listview with SQL data. but when it does not, I want to let the user go to another page (cancel.html). Here is my code. view.py class DbList(ListView): def get_queryset(self): try: subscription = stripe.Subscription.retrieve(stripe_customer.stripeSubscriptionId) print(subscription.status) if subscription.status == "active": sql = 'select * from test_eu' msg = "abcdefg" sql += " where eng_discription ~ '.*" + msg +".*' ORDER BY image_amount DESC " object_list = TestEu.objects.raw(sql) return object_list except: return render(request, 'cancel.html') The error message is NameError name 'request' is not defined So I tried to change the code return render(request, 'cancel.html') to return render(self.request, 'cancel.html') Then another error message occurred. TypeError object of type 'HttpResponse' has no len() How can I let the user go to another page in Listview?? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. -
Django return filtered manytomany field
class Person(models.Model): id = models.IntegerField(unique=True,null=False,primary_key=True,blank=False) name = models.CharField(max_length=10,null=False) username = models.CharField(max_length=10,unique=True) class Attend(models.Model): date = models.DateField() people = models.ManyToManyField(Person,related_name="attend",through='attendperson') i want to return Person with only filter Attend (by date ) for ex: p = Person.objects.get(id=1) #some code here to filter attend by *date* serial= PersonSerializer(p) #return Person with filtered Attend not all Attend Note: p.attend.filter(date__gte='2021-06-16') doesn't do the trick -
Django MySQL raw query does not return results
I'm trying to run a raw query in Django. I am not allowed to use ORM. I use Django MySQL backend. If I do basic queries, without parametrizing, the database returns results without problems. The query I want to run (not returning any results): from django.db import connection def get_data(variant): results = [] cursor = connection.cursor() cursor.execute("SELECT b.spec_id, b.h_loss, c.gen_type FROM `db-dummy`.spec_gen_data c JOIN `db-dummy`.gen_info a ON a.record_id = c.gen_id JOIN `db-dummy`.spec_data b ON b.record_id = c.spec_id WHERE b.h_loss = 1 AND (a.ref_gen = %s OR a.detail_ref_gen = %s) AND c.gen_type BETWEEN 1 AND 5 ORDER BY a.gen_name;", ('{}%'.format(variant),'{}%'.format(variant),)) columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results Is there something wrong with the syntax? I am not getting any error, just results = [] after executing the query and I am sure that that query should return results. -
405 method not allowed, Django + ngrok, only on my local machine
This is a legacy project that I'm working with other guys in my current job. and is doing a very strange behavior that I cannot understand. It's returning 405 http response status, which does not make sense, because this view already accepts POST requests I would share a couple of snippets, I just detected that happens just in the comment that I would mark. this is the view file, that actually accepts both methods GET and POST @csrf_exempt @load_checkout @validate_cart @validate_is_shipping_required @require_http_methods(["GET", "POST"]) def one_step_view(request, checkout): """Display the entire checkout in one step.""" this is the decorator that modifies the response, and returns 405. def load_checkout(view): """Decorate view with checkout session and cart for each request. Any views decorated by this will change their signature from `func(request)` to `func(request, checkout, cart)`.""" @wraps(view) @get_or_empty_db_cart(Cart.objects.for_display()) def func(request, cart): try: session_data = request.session[STORAGE_SESSION_KEY] except KeyError: session_data = '' tracking_code = analytics.get_client_id(request) checkout = Checkout.from_storage( session_data, cart, request.user, tracking_code) response = view(request, checkout, cart) # in this response it returns 405. if checkout.modified: request.session[STORAGE_SESSION_KEY] = checkout.for_storage() return response return func Any idea or clue when I can start to find out the problem?. for the record: I didn't code this, this was working a … -
How to change background color in Django Admin Dashboard
Please tell me how to change background color in django admin dashboard. And maybe all. -
Why is 'heroku run bash' command not keeping the changes after exit?
I've a django project deployed on Heroku, I'm trying to update its database but it requires the migrations to be deleted. I'm trying to delete using heroku run bash and then rm command. But it does not keep the changes after I exit from bash (see screenshot). Please tell what is wrong and is there any other way to delete those migrations?. Thanks. Migration files come back on returning - Screenshot -
form dont save data in django
i am using django's built-in contrib.auth User model and have setup a foreignkey and primary key relationships to a user for a Candidat model class Candidat(models.Model) : sexe = ( ('FEMELLE','FEMELLE'), ('MALE','MALE') ) prenom = models.CharField(max_length=100,null=True) nom = models.CharField(max_length=100 ,null= True) Email = models.EmailField(null= True) Telephone = models.CharField(max_length=100,null= True) age = models.IntegerField(null= True) dateNaissance = models.DateField(null= True) lieuNaissance = models.CharField(max_length=100, null=True) Nationalite = models.CharField(max_length=100,null=True) Addresse = models.CharField(max_length=100,null=True) Image = models.ImageField(max_length=100,null=True,upload_to='media') Telephone = models.CharField(max_length=100,null=True) sexe= models.CharField(max_length=120,null=True,choices=sexe) site = models.CharField(max_length=100,null=True) linkedin = models.CharField(max_length=100,null=True) # user = models.ForeignKey(User, null= True, on_delete=models.SET_NULL) user = models.OneToOneField(User, primary_key=True,on_delete=models.CASCADE,unique=True,related_name="candidat") def __str__(self): return f"candidature: {self.nom}" when i try to Save candidat informations in database that's dont match! forms.py class CandidatForm(ModelForm): class Meta: model=Candidat fields="__all__" exclude = ["user"] class UserForm(ModelForm): model = User fields:'__all__' views.py def create(request): candidat = request.user.candidat # print(request.user) form=CandidatForm(instance = candidat) # if request.method=='POST': # print(request.POST) form=CandidatForm(request.POST,request.FILES) if form.is_valid(): form= form.save(commit=False) formt.user = UserForm.objects.get(id=request.user.id) form.save() return redirect('coordonnées') context={'form':form} return render(request, 'pages/candid_form.html',context) the signals file create for me an instance candidat but it is empty please help help help me signals.py from .models import Candidat from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # @receiver(post_save,sender = User) def post_save_create_candidat(sender, instance, created, **kwargs): … -
How to stop browser redirect from CBV Django
I am in the process of switching everything from plain Django/HTML/CSS to JS with AJAX on some parts of my site. The problem I am running into is that with FBVs I can return an HTTPResponse i.e. return render(request, template, context) and use my JS to update the page; but with CBVs it seems to always redirect to the page when it gets the response. How can I stop it from redirecting? I have tried updating the get method to return the HTTPResponse the way a FBV would: class FilteredList(ListView): model = Item template_name = 'item/filtered_list.html' def get(self, request, *args, **kwargs): queryset = self.get_queryset() context = {'filtered_list': queryset} return render(request, self.template_name, context) def get_ordering(self, *args, **kwargs): ordering = self.request.GET.get('ordering', 'end') return ordering and the JS: function loadResults(e) { e.preventDefault(); $.get({ 'url': resultsURL + id + '/' }).done( function (data) { document.getElementById('resultsContainer').innerHTML = data; }) document.getElementById("resultsContainer").style.display = "block"; } ript> But this does not stop the redirect. how can I handle AJAX in CBV without the redirect? -
django second request in queue until first request complete
I'm new to django, tried to understand how multiple request can handle at the same time. i have app with two html and two different function and i put sleep 40 sec for one function ( one.html) and second function no sleep just render the html (second.html). opened one.html in one browser and second.html in another browser ( shows nothing ), because one.html will wait for 40 sec to complete. Django: 3.2.3 Runserver: python manage.py runserver ip:port Tried uwsgi but multi request not working: uwsgi --http --module app.wsgi --processess 4 --master --threads 2 Appreciated for any ideas/solutions provided. -
Get form values (foreign key field) in django
I'm trying to add the foreign key options to a select input but don't know how to get it. I want to make the same as using the form generated by Django, but with my own HTML. The form is for creating a new "patient". This is are the foreignkeys from my patient model: ubication = models.ForeignKey(Ubication, on_delete=models.CASCADE) supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) And this is the patient form: class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['dni', 'first_name', 'last_name', 'birth', 'risk', 'status', 'ubication', 'supervisor'] widgets = { 'dni': forms.NumberInput(attrs={'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'birth': forms.DateInput(attrs={'class': 'form-control'}), 'risk': forms.CheckboxInput(attrs={'class': 'form-control'}), 'status': forms.Select(attrs={'class': 'form-select'}), 'ubication': forms.Select(attrs={'class': 'form-select'}), 'supervisor': forms.Select(attrs={'class': 'form-select'}) } For example, here I want to add the supervisors from the supervisor model to vinculate it to the patient model: <select class="form-select" aria-label="Default select example" required name="supervisor" id="id_supervisor"> <option selected>Select supervisor</option> {% for f in form.supervisor %} <option value="{{f.id}}">{{f.first_name}}</option> {% endfor %} </select> -
Django modal bootstrap not displaying
I have been blocked on this problem for several days. I have bootstrap 3.3.7 in the project root folder. I am rendering some buttons in the django template that should open modal windows when clicked. But the modal functionality is not working. I am following the examples shown on this page: https://www.quackit.com/bootstrap/bootstrap_3/tutorial/bootstrap_modal.cfm Here is the template code: <h6> <button type="button" class="btn btn-sm" data-toggle="modal" data-target="#smallShoes"> DCCRP 2102 </button> <!-- The modal --> <div class="modal fade" id="smallShoes" tabindex="-1" role="dialog" aria-labelledby="modalLabelSmall" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title" id="modalLabelSmall">Modal Title</h4> </div> <div class="modal-body"> Modal content... </div> </div> </div> </div> </h6> Inside my base.html ... section, I have the following: {% load static %} <link rel="stylesheet" href="{% static '/boot/css/bootstrap.css' %}"> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static '/custom/custom.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> Thanks!