Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SearchFilter misbehaves when data is a lot
I tested the SearchFilter when I had around 10 records , and it was working fine, but I went ahead and tested it when the data records are above 200, it just returning the same data without searching or filtering the data , below is my View file : class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.filter(status=APPROVED) serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly) filter_backends = [DjangoFilterBackend, filters.SearchFilter] filter_fields = ('title', 'body', 'description',) search_fields = ( '@title', '@body', '@description', ) def filter_queryset(self, queryset): ordering = self.request.GET.get("order_by", None) author = self.request.GET.get("author", None) if ordering == 'blog_views': queryset = queryset.annotate( address_views_count=Count('address_views')).order_by( '-address_views_count') if author: queryset = queryset.filter(owner__email=author) return queryset This is how I search : /api/v1/blogs/?search=an+elephant But it just returns back all the data instead of filtering. -
InMemoryUploadedFile corrupted in server
I am creating an API with django REST Framework and I am having this problem when creating and endpoint. I am getting the file with file_details = request.FILES.get('file'). When I run the code on my machine, the file_details.size is 12679, but when I upload the code on the server the file_details.size is 21370 with the exact same file! Can anyone tell me why is this happening? Thanks in advance. -
Python based search engine or Elastic Search
In our project, we want to incorporate a search engine like ES/Solr for various use cases. Our backend stack is Python/Django. ES has a Java dependency. Is it advisable to use more popular and robust search engines like Elastic Search/Solr or use a native one like Whoosh or any other (suggestions welcome) -
How to do total on Django models.p
I am Trying to get total but i don't know why i am not getting the total and i have the code of models.py and it's output class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) table_num = models.CharField(max_length=50) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def total(self): total = 0 for order_item in self.items.all(): total += order_item.get_total_item_price() return total -
View saving to same model but different instances - not working
I have a view that saves form details through a html page to two different Person objects (which have different IDs), but which reside in the same table (on different rows) View person = Person.objects.filter(pk = user.related_person_id).first() medical_emergency_person = Person.objects.filter(related_entity=medical_emergency_entity).first() if request.method == "POST": form1 = PersonUpdateForm(request.POST, instance=person) form5 = MedicalPersonUpdateForm(request.POST, instance=medical_emergency_person) form1.save() form5.save() else: form1 = PersonUpdateForm( initial= { "title": person.title, "first_name": person.first_name, "last_name": person.last_name, "alias": person.alias } ) form5 = MedicalPersonUpdateForm( initial= { "title": medical_emergency_person.title, "first_name": medical_emergency_person.first_name, "last_name": medical_emergency_person.last_name, } ) context['personal_person_form'] = form1 context['personal_medical_emergency_person_form'] = form5 Forms class MedicalPersonUpdateForm(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Person fields = ('title', 'first_name', 'last_name') labels = { 'title': _("Title*"), 'first_name': _("Emergency Contact First Name*"), 'last_name': _("Emergency Contact Last Name*") } # FORM INITIALISATION TO SET HTML STYLING def __init__(self, *args, **kwargs): super(MedicalPersonUpdateForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['class'] = 'input' self.fields['first_name'].widget.attrs['class'] = 'input is-danger' self.fields['last_name'].widget.attrs['class'] = 'input is-danger' class PersonUpdateForm(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Person fields = ('title', 'first_name', 'last_name', 'alias') labels = { 'title': _("Title*"), 'first_name': _("First Name*"), 'last_name': _("Last Name*"), 'alias': _("Alias") } # FORM INITIALISATION TO SET HTML STYLING def __init__(self, *args, **kwargs): super(PersonUpdateForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['class'] = 'input' self.fields['first_name'].widget.attrs['class'] = 'input is-danger' self.fields['last_name'].widget.attrs['class'] … -
Can I get third party API fields as Foreign key to my Django Model?
That's true we can make foreign key relationships between models in Django. How about grabbing some fields from third party API fields as Foreign key for a specific Django model? Here is my Django model budiness_process.py class BusinessImpact(models.Model, ModelWithCreateFromDict): client = models.ForeignKey( accounts_models.Client, on_delete=models.CASCADE) business_process = models.ForeignKey( BusinessProcess, on_delete=models.CASCADE) hierarchy = models.CharField(max_length=255) business_assets = models.CharField(max_length=255) asset_name = models.CharField(max_length=255) vendors = models.CharField(max_length=255) product = models.CharField(max_length=255) version = models.CharField(max_length=10) cpe = models.CharField(max_length=255) asset_type = models.CharField(max_length=10) asset_categorization = models.CharField(max_length=255) asset_risk = models.CharField(max_length=50) _regulations = models.TextField(blank=True) _geolocation = models.TextField(blank=True) def __str__(self) -> str: return self.hierarchy + " - " + self.business_assets Here is my serializer.py class BusinessImpactSerializer(serializers.ModelSerializer): business_process = BusinessProcessListSerializer() class Meta: model = models.BusinessImpact fields = "__all__" Here is third API implementation for retrieving some of it's fields. @api_view( ["GET"], ) def cve_summery(request, key): r = requests.get( "https://services.nvd.nist.gov/rest/json/cves/1.0?cpeMatchString={}".format( key) ) if r.status_code == 200: result = [] res = r.json().get("result").get("CVE_Items") for rs in res: data = { "VulnID": rs.get("cve").get("CVE_data_meta").get("ID"), "Summery": rs.get("cve").get("description").get("description_data"), "exploitabilityScore": rs.get("impact") .get("baseMetricV2") .get("exploitabilityScore"), "severity": rs.get("impact").get("baseMetricV2").get("severity"), "impactScore": rs.get("impact").get("baseMetricV2").get("impactScore"), } result.append(data) return Response(result) return Response("error happend", r.status_code) So my intention here is, can I get "severity": rs.get("impact").get("baseMetricV2").get("severity") as Foreign key in my BusinessImpact model? Thanks! -
Django Rest Framework filtering a field with null and multiple values
I am using Django Rest Framework and want to filter the queryset in a view based on a certain field name, where the filter values would be null and additionally any other particular value for the field blog_category which is a ForeignKey value class Blog(ListCreateAPIView): permission_classes = [DjangoCustomModelPermissions] queryset = Blog.objects.all().select_related("blog_category") serializer_class = Blog_Serializer pagination_class = CustomPageNumberPagination filterset_fields = {'blog_category': ['isnull', 'exact', 'in']} I have added the lookup fields isnull to filter null values I have tried the following url requests but they do not work /?blog_catgeory__in=1,null /?blog_catgeory__in=1,isnull /?blog_catgeory__in=1,isnull=true How do I get this work? -
How to solve ssl certificate error in python code that is used to upload nft on opensea?
Traceback (most recent call last): File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 1348, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1282, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1328, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1277, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1037, in _send_output self.send(msg) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 975, in send self.connect() File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1454, in connect self.sock = self._context.wrap_socket(self.sock, File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 512, in wrap_socket return opener.open(url, data, timeout) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 519, in open response = self._open(req, data) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 536, in _open result = self._call_chain(self.handle_open, protocol, protocol + File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 496, in _call_chain result = func(*args) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 1391, in https_open return self.do_open(http.client.HTTPSConnection, req, File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 1351, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)> PS C:\Users\Jatin\Downloads\bulk-upload-to-opensea-main> -
Django rest framework drf-yasg swagger multiple file upload error for ListField serializer
I am trying to make upload file input from swagger (with drf-yasg), when i use MultiPartParser class it gives me error drf_yasg.errors.SwaggerGenerationError: FileField is supported only in a formData Parameter or response Schema My code: class AddExperience(generics.CreateAPIView): parser_classes = [MultiPartParser] permission_classes = [IsAuthenticated] serializer_class = DoctorExperienceSerializer serializer: class DoctorExperienceSerializer(serializers.Serializer): diploma = serializers.ListField( child=serializers.FileField(allow_empty_file=False) ) education = serializers.CharField(max_length=1000) work_experience = serializers.CharField(max_length=1000) i also tried FormParser but it still gives me same error. also FileUploadParser parser but it works like JsonParser. -
Custom User Model in django login with phone
I wanted to personalize the Django user model and authenticate users with a phone number How is it possible? -
django admin panel deploy on server Forbidden (403) CSRF verification failed. Request aborted
I'm on course Test-Driven Development with Django, Django REST Framework, and Docker (Michael Herman). My problem is that in a locally running container, the admin panel opens without problems, but the container placed on heroku gives an error (Forbidden (403) CSRF verification failed. Request aborted.) .. Where to look? Thanks! -
Django deployment on pythonanywere
I did the deployment of my django app on pythonanywhere but i see that i have a probleme with relative path . this app can upload and save 2 files in a directory my code actually is: from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict def home(request): #upload file and save it in media folder if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = FileSystemStorage() #save files name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'\\media\\'+name file_directory2 = d+'\\media\\'+name2 results,output_df,new =results1(file_directory,file_directory2) i gived this error FileNotFoundError at / [Errno 2] No such file or directory: '/home/VIRAD\\media\\Listing /home/VIRAD/Django1/viruss/views.py, line 26, in home results,output_df,new =results1(file_directory,file_directory2) -
Limit anonymous petitions in Django
I have a landing page when you can get budgets. I am using JS/HTML in Frontend and Django in Backend. I would like to limit the petitions to anonymous users, because you do not have to be register to get the budgets. I get the IP like this: def visitor_ip_address(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip The point is, I do not know if is the best way to get a IP from one session or the same laptop, for limit it. My goal is limit the petitions in incognito navigation as well, from the same laptop. How is the best way to do it? Thanks -
How to increase file upload size in Django application running on EC2 instance with Nginx as revese Proxy?
I've a Django application that is running on EC2 instance. It is uploading file upto 100MB without any problems, but above 100MB file size, it gives error 413 Request Entity Too Large. I've tried in file /etc/nginx/sites-available/default under server configuration. client_max_body_size 10G; I've also applied the same configuration in my domain configuration files, but all in vein. This configuration works well in my other servers, where I am running php applications. Note: I've used gunicorn with supervisor for running Django application. -
get kwargs in test of serializer
I wrote a serializer in which I used the kwargs in its validate() . here is it: def validate(self, value): course_id = self.context.get("view").kwargs.get("course_id ") .... now I want to write a test but I don't know how to pass the kwargs to it. here is the test I am trying to write: def test_valid_data(self): serializer = CategorySerializer( data=self.category, ) self.assertTrue(serializer.is_valid()) I test this but it didn't work: def test_valid_data(self): serializer = CategorySerializer( data=self.category, kwargs={ "course_id": test_course_id }, ) self.assertTrue(serializer.is_valid()) -
access a Url with a query inside a modal
I want to open the content of a page inside a modal, but this page is accessed by a query string like: add_data?filter=crew So, my modal needs to access the page, but I can't include a url, just a html page: <button id="myBtn">+ Add</button> <div id="myModal" class="modal"> <div class="modal-content"> <span class="close">&times;</span> {% block survey_index %} {% include 'add_data?filter=crew' %} #It doesn't work {% end block %} </div> </div> This way doesn't work since the include expects me to pass a html page like: {% block sample_unit_type_index %} {% include 'inv/index/example.html' %} {% endblock %} How to access the page that is in add_data?filter=crew url code: path('add_data', add_data, name="add_data"), views.py return return render(request, 'inv/add_new.html', context) So the page add_new.html has the content accessed by the queries. Example: <a href="add_dados?filter={{path_info}}" class="btn3 add" role="button">Add</a> Any suggests to access the add_data?filter=crew page content in modal? -
How to integrate google analytics to a Django website dashboard?
I have linked my website hosted on heroku to google analytics. I want to display all the analytics on the dashboard of my website. I tried every stack overflow answer but nothing seemed to work for me. Can anyone please help? Here is a link to my website - sym-fi.herokuapp.com Here is a pic of the django directory I did find this package [https://pypi.org/project/django-google-analytics-app/], but I don't know how to use it. I'm a newbie in coding and I'll appreciate if you guys help me out. Thanks -
Can programmatically upload objects to S3 bucket but GET request is forbidden
I'm writing a django app which needs file uploads. I've created an S3 bucket and an IAM user with S3FullAccess permissions. I took the access key ID and the secret access key and put them in my code (using env variables). I'm using django_storages to send uploaded files to S3, and my config in my settings file is AWS_ACCESS_KEY_ID = os.environ.get('S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('S3_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = '<my bucket name>' AWS_S3_REGION_NAME = 'ap-south-1' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' The CORS policy for the bucket for now is [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "POST", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Using this configuration, I'm able to upload files to the S3 bucket from my application, but when that file is requested by the application, I get a 403 Forbidden error. How can I fix this? -
how show error message csv file does not exist
if i added a csv file name inccorrectly i wnat to show error message entered csv file does not exist please write the correct csv file name.how it make? class Command(BaseCommand): help = 'Load a company csv file into the database' def add_arguments(self, parser): parser.add_argument('filename.csv', type=str) def handle(self, *args, **options ): if Company.objects.exists(): print("Data already loaded!!") with open('companies.csv', 'r') as file: reader = csv.reader(file) for row in reader: create= Company.objects.get_or_create( name=row[0], hr_name=row[1], hr_email=row[2], hr_verified=row[3], user_id=row[4], primary_phone=row[5], comments=row[6], ) -
Need to restrict the access for staff users to view and edit only their inputted data in django admin
I need to restrict the access in the admin page like if a staff user is logging in the admin they need to see only their entry data's and can able to add or delete their data in the admin panel. As I tried the below code in the admin.py still I could able to view and delete everyone's data. Admin.py admin.site.site_header = "Inhouse Project Management" admin.site.site_title = "TimeSheet Admin Portal" admin.site.index_title = "TimeSheet Administration" TokenAdmin.raw_id_fields = ['user'] class MyModelAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) #Admin SuperUser @admin.register(User) class UserAdmin(ImportExportModelAdmin): list_display = ('id','employee_name','email','billable_and_non_billable','designation') search_fields = ['employee_name'] pass @admin.register(Project) class ProjectAdmin(ImportExportModelAdmin): list_display = ('id','project_name','client','start_date','end_date') search_fields = ['project_name'] pass Urls.py urlpatterns = [ path('', TemplateView.as_view(template_name="social_app/index.html")), #social_app/index.html path('admin/', admin.site.urls), #admin api path('api/',include(router.urls)), #api path('accounts/', include('allauth.urls')), #allauth re_path('rest-auth/', include('rest_auth.urls')), #rest_auth path('api-auth/', include('rest_framework.urls')), re_path('rest-auth/registration/', include('rest_auth.registration.urls')), #path('api-token-auth/', views.obtain_auth_token), #path('api-token-auth/',CustomAuthToken.as_view()), #path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('auth/login/',TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('conso/',view), path('chaining/', include('smart_selects.urls')), ] models.py class User(models.Model): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.CharField(max_length=50) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) class Meta: db_table ='User' def __str__(self): return self.employee_name serializers.py class … -
Unable to login Django admin with valid credential, also user is erratically showing logged in and logged out on refresh in DRF view
My problem closely relates to Unable log in to the django admin page with a valid username and password one more thing I noticed while trying to login into DRF login panel that after login, it is not showing logged in user in right side.... but on refreshing it is showing then again refreshing it is not showing... usually initially user is getting logged in and logged out automatically on alternate refresh and this behavior becomes erratic sometimes and user logged in is not showing on alternate refresh. You can try this on: Admin Login page: https://www.markonmap.com/admin DRF Login page: https://markonmap.com/api-auth/login/?next=/map/mappoint/1 username: leader password: abcd.1234 I have tried everything suggested in the answers of aforementioned following question Unable log in to the django admin page with a valid username and password I have cleaned all my browser history, cookies and cache... tried login through incognito I have flushed my session actually all tables of my database. but problem persists. Config for authentication backend AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] I am using Django 3.2 -
django-tenants: Newly created app’s migrations are reflecting as expected in public schema of the database, but not in tenant-specific schemas
We had authored two applications since the beginning the project* The same has been part of the multi-tenancy architecture in a single database, semi-isolated fashion using a multi-schema approach. We have built a third application that we also want to integrate into django-tenant schemas that’s failing to reflect their tables in the database, in tenant-generated schemas. However, the migrations for the newly created app is successfully migrating and creating tables in the public schema. The same is failing to reflect in tenant-generated schemas. This is happening for any new app that is created through Django. We are using PostGIS as original backend and django-tenants as database engine. Current Django version=3.2.12 Current PostgreSQL version=12 Current django-tenants=3.4.1 -
django makdmigrations raise error after remove a function in models.py
I define a model named Foo which has a FileField named bar, and I define a function baz which is callable used for bar's upload_to arguement in same file. When I removed the bar field and baz funcion and perform makemigrations operations, it raise error "AttributeError: module 'models' has no attribute 'baz'". How can I solve the bug? below is snippet demo import os import time from django.db import models def baz(instance, filename): ext = filename.split('.')[-1] fn = time.strftime('%Y%m%d%H%M%S') com = fn + '.' + ext return os.path.join('', com) class Foo(models.Model): name = models.CharField(max_length=255) bar = models.FileField(upload_to=baz) # wants to remove -
Getting Time data to Jinja2 without leading zero
I'm using PostgreSQL with Django to save a time data to DB with html time input like this <input type="time" name="houmon_time" value="{{ kokyaku.houmon_time.0 }}"> which works fine and data are saved in DB like this 09:00:00, but when I'm trying to GET the data to {{ kokyaku.houmon_time.0 }} data are parsed like <input type="time" name="houmon_time" value="9:00"> and I'm getting an error in browser console because of that leading zero The specified value "9:00" does not conform to the required format. The format is "HH:mm", "HH:mm:ss" or "HH:mm:ss.SSS" where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. I'm getting data from DB like this def get_details(self): if self.pk is not None and self.connection is not None: kokyaku_details = pd.read_sql( sql=f"SELECT * FROM cs_houmon_ WHERE code='{self.pk}'", con=self.connection ) kokyaku_details = kokyaku_details.to_dict('list') return kokyaku_details # and this # ... snipped kokyaku_list = list(kokyaku_instance.get_new()) if len(kokyaku_list) == 1: print(kokyaku_list) return render(request, self.template, self.context) column_names = [x.replace("\n", "") for x in kokyaku_list[0].split(",")] kokyaku_list = [x.split("\n") for x in kokyaku_list[1:]] new_kokyaku = [] for small_list in kokyaku_list: for val in small_list: if len(val) > 0: val = val.split(",") try: val[5] = val[5].split(".")[0] val[5] = datetime.datetime.strptime(val[5], "%Y-%m-%d %H:%M:%S") if val[5].year == 1999: … -
Popup With JavaScript not working with Django template
The follow code is not running in a Django project. Is there any limitation when using popups in django? In this case, the white window does not open with the text. Why doesn't the Django template open the div with the text? Apparently the css and javascript are being called and the screen in the background darkens, but the white window with the text does not appear. const openModalButtons = document.querySelectorAll('[data-modal-target]') const closeModalButtons = document.querySelectorAll('[data-close-button]') const overlay = document.getElementById('overlay') openModalButtons.forEach(button => { button.addEventListener('click', () => { const modal = document.querySelector(button.dataset.modalTarget) openModal(modal) }) }) overlay.addEventListener('click', () => { const modals = document.querySelectorAll('.modal.active') modals.forEach(modal => { closeModal(modal) }) }) closeModalButtons.forEach(button => { button.addEventListener('click', () => { const modal = button.closest('.modal') closeModal(modal) }) }) function openModal(modal) { if (modal == null) return modal.classList.add('active') overlay.classList.add('active') } function closeModal(modal) { if (modal == null) return modal.classList.remove('active') overlay.classList.remove('active') } *, *::after, *::before { box-sizing: border-box; } .modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0); transition: 200ms ease-in-out; border: 1px solid black; border-radius: 10px; z-index: 10; background-color: white; width: 500px; max-width: 80%; } .modal.active { transform: translate(-50%, -50%) scale(1); } .modal-header { padding: 10px 15px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px …