Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Can I make genre selection tables for three different tables that have different genre?
as in the title, I would like to make a separate single table for the genres of movies, books and CDs. When creating a product, I would like to limit the choice of genre depending on what kind of product we want to make. Is this idea of making one table good? Or is it better to make three separate ones. I will add that all product models inherit from the product. At the moment it looks like this from polymorphic.models import PolymorphicModel from django.db import models from django.urls import reverse from django.core.exceptions import ObjectDoesNotExist class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Disco', 'Disco'), ('Electronic music', 'Electronic music'), ('Rap', 'Rap'), ('Reggae', 'Reggae'), ('Rock', 'Rock'), ('Pop', 'Pop'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) def full_clean(self, exclude, validate_unique=True, validate_constraints=True): if CD.objects.filter(genre=self.genre, tracklist=self.tracklist).exists(): ValueError('Within one genre, we cannot offer two albums with the same track list') try: cds = CD.objects.filter(band=self.band) tab = [] for cd … -
Django taking too long to initialize middleware
I'm investigating some slow requests in our server using Datadog frame graphs. I found an interesting thing: this long delay to initialize/call the Django middleware stack. Any idea of what might be causing this issue/delay? -
how to put actions on a command in django?
I have a models django command which has a status field which should normally allow the administrator to put actions such as (on hold, validate reject or still in processing when a customer places an order but I don't know how to proceed to implement it please help me. my command models from django.db import models from user.models import User from main.models import * class Command(models.Model): class Status(models.TextChoices): PENDING = "PENDING" REJECTED = "REJECTED" CANCELED = "CANCELED" PROCESSING = "PROCESSING" READY = "READY" DELIVERED = "DELIVERED" user = models.ForeignKey(User, on_delete=models.CASCADE) cart = models.ForeignKey( Cart, verbose_name="panier", on_delete=models.CASCADE) type = models.CharField(max_length=50) data = models.JSONField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=20, choices=Status.choices, default="PENDING") email = models.EmailField(max_length=50, null=True) phone = models.CharField(max_length=60) name = models.CharField(max_length=30) company = models.CharField(max_length=50, default='') address = models.CharField(max_length=100, default='') appartement = models.CharField(max_length=100, default='', null=True, blank=True) city = models.CharField(max_length=50, default='') country = models.CharField(max_length=50, default='') here is the view, here I can't put anyone, I have no idea def command_action(request , act): action = get_object_or_404 (Command,id = act) if request.method == "POST": action I can't find an algorithm to solve this help me with some ideas -
Not able to run two consumers simultaneously using Django Channels
consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import asyncio class WebSocketConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): print(f"*********{text_data}*****") asyncio.create_task(self.send_count()) # run send_count in a separate task async def send_count(self): for i in range(0, 100000): print(i) await self.send('count completed') print('count completed') class SecondConsumer(AsyncWebsocketConsumer): async def connect(self): print("\n\n\n\n\n\n\n\n\n Reaching second consumer"\n\n\n\n") await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): await self.send('you are connected to socket') routing.py from django.urls import re_path from . import consumers websocket_urlpatterns=[ re_path(r'ws/1/', consumers.WebSocketConsumer.as_asgi()), re_path(r'ws/2/',consumers.SecondConsumer.as_asgi())] when WebSocketConsumer is running for loop if I try to run SecondConsumer from a new tab I am not able to connect to the websocket. I want to run both consumers from different browser tabs simultaneously -
How to study Python for Machine learning from scratch?
I am currently Studying in College , My first semester is over and I want to learn Python for machine learning with my College Degree, they are teaching C++ in college , Plz guide me! I tried learning it myself but couldnt manage time so plz guide me -
Celery beat creating multiple instances of the same task Django
This has been asked quite a few times but I couldn't find a satisfactory solution so requesting for help after searching for several hours I have defined celery broker with rabitmq and backend with redis. Earlier broker was with redis however it was giving the problem of multiple instances even without celery beat. This is a known issue When i am using celery beat, the issue is resurfacing This is my celery beat in settings.py of django project CELERY_BEAT_SCHEDULE = { 'update-every-minute': { 'task': 'apiresult.tasks.update_database', 'schedule': 60.0, }, } Am calling the async task from apps.py of the apiresult app from django.apps import AppConfig class ApiresultConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apiresult' def ready(self): from apiresult.tasks import update_database update_database.delay() tasks.py in apiresult app contains the update_database function @shared_task def update_database(): I have read we can use distributed locks to achieve it, but is there a simpler way to ensure only one instance of a task runs. I have tried celery redbeat but thats not helping either. Any help here is appreciated -
I cant install django-jquery : No matching distribution found for django-staticfiles-jquery
I have this version of python : Python 3.10.7 and this version for django : 3.2.15 I want to install jquery using : pip install django-staticfiles-jquery but i got this : ERROR: Could not find a version that satisfies the requirement django-staticfiles-jquery (from versions: none) ERROR: No matching distribution found for django-staticfiles-jquery I dont know what's the problem -
Django makemigrations throws error because unknown field
I am working on my first wagtail app. I already got some issues with the migrations. I wanted to chagne the models.ImageField to ImageChooserBlock() after I already did the first migration. This is my new model: class AboutPage(Page): template= "event/about.html" text = RichTextField() team_photo = ImageChooserBlock() content_panels = Page.content_panels + [ FieldPanel('team_photo'), FieldPanel('text'), ] But this throws the following error in the console: django.core.exceptions.FieldError: Unknown field(s) (group_foto) specified for AboutConnectedPage After running makemigrations. What could be the problem? -
Writing data to django database
I have a website project, but it is still raw. The problem is that I wrote a separate user registration page and the data from this page is written to the data table, but as soon as in forms.py I add additional parameters such as - there are at least 8 characters in the password, then the data stops being written to the database. I've tried everything I can, I've added this to the template form {% if form.errors%}. But stupidly there is no mistake. And I also gradually cleaned up for each parameter, but it didn't help either. I came here to find out what the error is, help me with all the necessary codes below, if you need something, write me I will throw it off. And I did migrations too This is forms.py users applications from .models import UserProfile from django import forms from django.forms import ModelForm, TextInput from django.core.validators import RegexValidator, EmailValidator class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = ['email', 'password', 'password2', 'first_name', 'last_name', 'phone_number'] widgets = { "email": TextInput(attrs={ 'class': 'form', 'placeholder': 'Email', 'type': 'text' }), "password": TextInput(attrs={ 'class': 'form', 'placeholder': 'Password', 'type': 'password' }), "password2": TextInput(attrs={ 'class': 'form', 'placeholder': 'rePassword', 'type': 'password' … -
gunicorn.sock failed (13: Permission denied) while connecting to upstream
On one of my django application hosted on AWS i have an issue with my gunicorn / nginx interraction. When i'm going on AWS instance's Public IPv4 DNS i have the error *3 connect() to unix:/home/ubuntu/gunicorn.sock failed (13: Permission denied) while connecting to upstream, client: myip, server: mywebsite.nd, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/gunicorn.sock:/ I'm stuggling on it for couple of days. /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/myapp ExecStart=/home/ubuntu/venv/bin/gunicorn \ --access-logfile - \ --workers 2 \ --bind unix:/home/ubuntu/gunicorn.sock \ myapp.wsgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/gunicorn.socket : [Unit] Description=gunicorn socket [Socket] ListenStream=/home/ubuntu/gunicorn.sock [Install] WantedBy=sockets.target I already test to put my gunicorn.sock on differents folders owned by user ubuntu without any success. My nginx conf is fine since it worked few days ago. My gunicorn.sock is always created by root:root. ls -la /home/ubuntu/gunicorn.sock srw-rw-rw- 1 root root 0 Mar 24 10:49 /home/ubuntu/gunicorn.sock Tried to chown ubuntu:www-data on it but when gunicorn.socket is restarted it recreated it with root:root. Btw on my others application it doesn't seem to be a problem. All solutions found on SO may pose as a serious security risk on my public facing server (changes nginx user to root, setsebool -P httpd_can_network_connect 1 etc..) so don't want … -
Django function update object not working, he is create new object instead update
this function generate new object instead update existing one, how can i modify to update? def brand_upd(request, slug): data = get_object_or_404(Brand, slug=slug) form = BrandForm(instance=data) if request.method == 'POST': form = BrandForm(request.POST, request.FILES, instance=data) if form.is_valid(): form.save() return redirect('contul_meu') context = {'form': form} return render(request, "brand/brand_create.html", context) this function does not work to modify an existing object but creates a new object. where can the problem be? -
Prefetch in models of complex relationships
Given the following models, I would like to get objects across the models in prefecth. class A(models.Model) b = models.ForeignKey("B", related_name="a") code = models.IntegerField(default=0) class B(models.Model) c = models.ForeignKey("C", related_name="b", blank=True, null=True) class C(models.Model) name = models.CharField(max_length=12) c_list = C.objects.prefetch_related( Prefetch( "b__a", queryset=A.objects.order_by("code"), to_attr="a_list", ) ) for c in c_list: print(c.a_list) The following error occurs AttributeError: 'C' object has no attribute 'a_list' I want to get an object of A directly from an object of C. How can I achieve this? Thanks in advance. -
Identifying Anonymous Users uniquely for custom Websocket communication in Django Rest Framework
I am using Django Rest Framework with ASGI capabilities. I have enabled a websocket. For each websocket connection, i get a channel_name which i suppose is unique. Nevertheless when i received a Request on http for example to do some calculation i am not able to understand how am i suppose to send it back to the right, unique Anonymous User. I have enabled Json Web Token JWT authentification and even though SessionMiddleware is added to my DRF, i dont get any Session Info (it is None in the request for session_key, the session doesn't exist). My goal was to associate a session_key to a channel_name in the database and when the calculation is finished to send back the results to the correct Anonymous User by Websocket with this mapping. Am i on the right path? Is there another solution since i cant get a session cookie or session at all. -
Django Custom filter doesn't register
Can't seem to get my custom template tag to work So I need a custom template tag in order to index variables in django templates, so I did this file structure templatetags __init__.py index_dict.py ... models.py views.py index_dict.py from django import template register = template.Library() @register.filter(is_safe=True) def index_dict(var, arg): try: return var[arg] except: return None and comments.html where is is being used {% if canUserEdit|index_dict:comment or canUserEdit %} <!-- Inner HTML --> {% endif %} The error is this TemplateSyntaxError at /post/1/ Invalid filter: 'index_dict' and it gets triggered in the html I don't understand what I'm doing wrong, it seems im following the documentation but nothing seems to work any ideas -
How to add css file to my css_settings in settings.y
I`m using django-select2 but its not important and i want to add some new css styles to that settings but if i add them i got an error because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. settings.py SELECT2_CSS = [ os.path.join(BASE_DIR, 'static_src/css/style.css') ] -
How can I use django EAV in the models
I want to create something similar to Microsoft Access Design View in Django model using the models below. After doing my own research, the only way to make that happen is by using Django EAV. However, as a beginner in Django, I don't actually know how to make that happen. class Type(models.Model): TYPE_OF_DATA = ( ('Number', 'Number'), ('character', 'character'), ('boolean', 'boolean'), ('date', 'date'), ('image', 'image'), ) data_type = models.CharField(max_length=1000, choices= TYPE_OF_DATA) def __str__(self): return self.data_type class Column(models.Model): name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete= models.CASCADE) class Table(models.Model): number = models.IntegerField() character = models.CharField(max_length=30) check_box = models.BooleanField() date = models.DateField() image = models.ImageField(upload_to='image-table') As you can see using Django modelFormSet I successfully created 30 Column in the form: From .forms import ColumnForm From django.forms import modelformset_factory def design(request): ColumnFormSet = modelformset_factory(Column, fields = ('name', 'selec_type'), extra=30) formset = ColumnFormSet if request.method == 'POST': formset = ColumnFormSet(request.POST) if formset.is_valid(): formset.save() return redirect('Home') else: formset = ColumnFormSet() return render (request, 'design.html', {'formset':formset}) Using this view, a user can create a name of a field and assign it to the data type that a user want the field to be stored. My problem here is the Table model, where user can store all the … -
How to post data from one model and retrieve to another model of the same app using Django rest framework
I have two models which are related by one to many relationship. I want to use the first model called BedNightReturn to post data and another one called BedNightReturnAssessment to calculate the data post and retrieve data. My models are as follows:- class BedNightReturn(models.Model): room_type = models.CharField(max_length=50) number_of_rooms = models.PositiveSmallIntegerField() price_per_night = models.DecimalField(max_digits=10, decimal_places=2) days_in_month = models.PositiveSmallIntegerField() class Meta: verbose_name = 'BedNightReturn' verbose_name_plural = 'BedNightReturns' def __str__(self): return f'{self.room_type}' class BedNightReturnAssessment(models.Model): assessment = models.ForeignKey(BedNightReturn, related_name = "assessments", on_delete=models.CASCADE) class Meta: verbose_name = 'BedNightReturnAssessment' verbose_name_plural = 'BedNightReturnAssessments' def __str__(self): return f'{self.assessment.room_type}' @property def potential_turnover(self) -> float: days_in_month = 30 return float(days_in_month) * float(self.assessment.number_of_rooms) * float(self.assessment.price_per_night) @property def actual_turnover(self) -> float: return float(self.assessment.days_in_month) * float(self.assessment.number_of_rooms) * float(self.assessment.price_per_night) And serializers are as follows:- class BedNightReturnSerializer(ModelSerializer): class Meta: model = BedNightReturn fields = ( 'id', 'room_type', 'number_of_rooms', 'price_per_night', 'days_in_month', ) class BedNightReturnAssessmentSerializer(ModelSerializer): assessment = BedNightReturnSerializer() potential_turnover = ReadOnlyField() actual_turnover = ReadOnlyField() class Meta: model = BedNightReturnAssessment fields = ( 'id', 'assessment', 'potential_turnover', 'actual_turnover', ) And views are:- class BedNightReturnViewSet(ModelViewSet): queryset = BedNightReturn.objects.all() serializer_class = BedNightReturnSerializer class BedNightReturnAssessmentViewSet(ModelViewSet): queryset = BedNightReturnAssessment.objects.all() serializer_class = BedNightReturnAssessmentSerializer And urls:- from django.urls import include, path from rest_framework import routers from bednightlevy.views import ( BedNightReturnAssessmentViewSet, BedNightReturnViewSet, ) router = routers.DefaultRouter(trailing_slash … -
Is there any way to have end to end type safety in a website with React and Typescript as the frontend and Django as the backend?
I want to build a website with NextJS as the frontend and Django as the backend. I wanted to know if there was any way to ensure client to server type safety in my stack. Although I have searched for many libraries, but there doesn't seem to be any. The closest library I found was mypy, which ensured type safety in the backend, but not between the server and the client like tRPC. -
'tuple' object has no attribute 'quantity' django
I'm trying to do a cart system where an user can add a product to the cart and if it was already in there I would add one of it but I keep getting the error "'tuple' object has no attribute 'quantity' django". class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) cart = models.BooleanField(default=True) order = models.BooleanField(default=False) class Orders(models.Model) : user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) def add_to_cart(request, pk) : item = get_object_or_404(Product, pk=pk) order_item = OrderItem.objects.get_or_create( item = item, user = request.user, order = False ) order_qs = Orders.objects.filter(user=request.user) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__pk=item.pk).exists() : order_item.quantity += 1 order_item.save() return redirect("product-detail", pk = pk) else: order.items.add(order_item) return redirect("product-detail", pk = pk) else: order = Orders.objects.create(user=request.user) order.items.add(order_item) return redirect("product-detail", pk = pk) -
DRF set auth_token to httponly cookie
I use djoser library for TokenAuthentication. But I don't want to send access_token to frontend. Because it can't save it in a secure way. So I changed TokenCreateView in this way: from djoser.views import TokenCreateView class TokenCreateView(TokenCreateView): def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token response = Response() data = token_serializer_class(token).data response.set_cookie( key = 'access_token', value = data['auth_token'], secure = False, httponly = True, samesite = 'Lax' ) response.data = {"Success" : "Login successfully","data":data} return response I put access_token to httponly cookies. And created a middleware: def auth_token(get_response): def middleware(request): # when token is in headers in is not needed to add in from cookies logger.error(request.COOKIES.get('access_token')) if 'HTTP_AUTHORIZATION' not in request.META: token = request.COOKIES.get('access_token') if token: request.META['HTTP_AUTHORIZATION'] = f'Token {token}' return get_response(request) return middleware MIDDLEWARE = [ ... 'apps.profiles.middlewares.auth_token', ... ] This middleware adds access_token from cookies to headers. Now the frontend doesn't have an accecc to auth_token. And it is more difficult to steal the auth_token. Is this approach appropriate? -
Timeout after 30s waiting on dependencies to become available: [tcp://mathesar_db:5432]
I tried running sudo docker compose --profile dev up but everytime it fails to bring the server up with the same exact reason - Timeout after 30s waiting. I also tried restarting the docker service and killing all the processes on port 5432, but it didn't help. [+] Running 3/0 ⠿ Container mathesar_db Created 0.0s ⠿ Container mathesar_service_dev Cr... 0.0s ⠿ Container mathesar-watchtower-1 C... 0.0s Attaching to mathesar-watchtower-1, mathesar_db, mathesar_service_dev mathesar-watchtower-1 | time="2023-03-24T06:55:57Z" level=debug msg="Sleeping for a second to ensure the docker api client has been properly initialized." mathesar_db | mathesar_db | PostgreSQL Database directory appears to contain a database; Skipping initialization mathesar_db | mathesar_db | 2023-03-24 06:55:57.217 UTC [1] LOG: starting PostgreSQL 13.10 (Debian 13.10-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit mathesar_db | 2023-03-24 06:55:57.218 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 mathesar_db | 2023-03-24 06:55:57.218 UTC [1] LOG: listening on IPv6 address "::", port 5432 mathesar_db | 2023-03-24 06:55:57.384 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" mathesar_db | 2023-03-24 06:55:57.550 UTC [26] LOG: database system was shut down at 2023-03-24 06:55:17 UTC mathesar_db | 2023-03-24 06:55:57.595 UTC [1] LOG: database system is ready to accept connections mathesar-watchtower-1 | time="2023-03-24T06:55:58Z" level=debug … -
How to use render_foo() in a table made with django-tables2 but for dynamically generated columns?
i have a table Comparativ that is created using django-tables2. In this table I use the __init__ method to generate columns dynamically by getting some unique values("nrsl") from a model(SLCentruDeCost). for col in extra_cols creates the columns with name of col. In these columns I need to make some calculations, example: getting the name of the column and filtering a model by that name and getting the sum of a attribute that correspond to the filter. class Comparativ(tables.Table): def __init__(self, data, **kwargs): slcd = SLCentruDeCost.objects.filter(centrudecost_id=self.pk).values_list('nrsl', flat=True).distinct() if slcd: extra_cols=[] extra_cols = slcd for col in extra_cols: self.base_columns[col] = tables.Column(accessor=f'nrsl.{col}', verbose_name=col.replace("_", " ").title(),orderable=False) # i should set the render method for each new column here, but i don't know how super(Comparativ, self).__init__(data, **kwargs) I know that there the possibility to use the render_foo() function to render the values for a specific column, but that does not help me with the dynamically generated columns. Please help -
Django session storage and retrieval not working, can't pass value within view
I have a django view that I am using to process a payment.. This view has two different 'stages', and will do something different depending on the value of stage which is passed as a hidden value on each. This is my view (trimmed down for this question) at the moment: def takepayment(request, *args, **kwargs): if request.method == 'POST': form = paymentForm(request.POST) stage = request.POST.get('stage', False); firstname = request.POST.get('firstname', False); if (stage == "complete"): firstname = request.session['firstname'] return render(request, "final.html", {'firstname': firstname) if (amount > 1): if form.is_valid(): firstname = form_data.get('firstname') request.session['firstname'] = firstname return render(request, "payment.html") else: if form.is_valid(): form_data = form.cleaned_data amount = form_data.get('amount') request.session['firstname'] = firstname return render(request, "payment.html", {'form': form, 'amount': amount}) return render(request, "payment.html") In the section of the view where stage == "complete", firstname always reports as false. I am unclear as to why the session is not storing the firstname variable. Everything seems to be working as it should (aside from the obvious), so I'm unsure why this isn't working. I also set SESSION_SAVE_EVERY_REQUEST to True in settings.py and ran manage.py migrate as it was a suggestion for someone having a similar issue, however it made no difference in this case. I have … -
I want to show the password on click the button in django
In django ,I want to show the password on click the button but It is working for only one field .I want to show the password on clicking the relative button Here is my template code {% if passwords %} <div class="body"> <div class="origin"> <input type="number" name="noofpwds" value={{no}} disabled hidden> <table class="table table-borderless" id="tab"><h1>your passwords </h1> <div class="parent"> {% for pwd in passwords %} <div> <input type="text" class="span"value={{pwd.field}} readonly> <input type="password" placeholder="type old password" value={{pwd.pwd}} id="pwd" class="input" required> <button class="btn btn-primary" onclick="showHide()" id="btn">show</button> </div> <script> function showHide() { var showText=document.getElementById("btn"); var input=document.getElementById("pwd"); if (input.getAttribute("type") === "password") { input.setAttribute("type", "text"); showText.innerText = "hide"; } else { input.setAttribute("type", "password"); showText.innerText = "show"; } } </script> {% endfor %} </div> <tr class="submit-btn"> <td > <a href="{% url 'updatepwd' %}" ><button class="btn btn-primary" type="submit">update password</button></a> </td> </tr> </table> {{passwords.pwd}} </div> </div> {% endif %} All buttons are working for only one field I want to show the password on clicking the respective button -
modal appearing with modal backdrop in side
I am new to html and trying to implement bootstrap modal dialog but modal backdrop(Not sure about the exact name) is appearing on left side of it ,how do i resolve this I have already tried these : z-index: 1; data-backdrop="false" Adding to body with $('#exampleModalLong').appendTo($('body')); this is my modal : <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-backdrop="false"> <div class="modal-dialog modal-dialog-centered" role="document" id="modalDocument"> <div class="modal-content" id="modalContent"> <div class="modal-header" id="modalHeader"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> the CSS i have configured with modal : #exampleModalLong { left: 0; right: 0; top: 0; bottom: 0; margin: auto; position: absolute; width: 75%; height: 75%; background: aqua; z-index: 1; } method to display modal : function displayModel(message) { $('#exampleModalLong').modal('show') } Please help me resolve this