Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Django RestFramework supports async views and class?
It will be helpful if someone helps me with a clear cut answer. If Yes any suggestion how to approach... coz, I try to use async with DRF but I am always ending with "AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'coroutine'>" this error -
How to add buttons instead of select element as action in django admin
hope everyone is doing well. I want to integrate ample admin template to django, so what I want is just customize the look and feel of django admin but not the behaviour. I want to show buttons like delete and other actions instead of select element that django admin comes with by default. Following is what django do to render the select element, I overriden admin templates but dont know what I do to get buttons instead of select items, I would love to mention that these actions are dynamic you know by customization of admin class, we can add different actions and so thats why we have this for loop. What output I am getting is as follow: This is what django generates: What I want is just render buttons instead of html select element, plz help -
Django - check_password() always returning False
I have written a test for creating user. This statement self.assertTrue(user.check_password(payload["password"])) is failing with this error, AssertionError: False is not true. user.check_password() is returning False even though both passwords are equal. class UsersAPITests(TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.client = APIClient() self.faker = Faker() def test_create_user(self): payload = { "email" : self.faker.email(), "password": self.faker.password(), "username": self.faker.user_name() } response = self.client.post(CREATE_USER_URL, payload) self.assertEqual(response.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**response.data) self.assertTrue(user.check_password(payload["password"])) self.assertNotIn('password',response.data) -
Trying to post blob data from js to django server
I have some (recorded as .webm)audio as blobs, and I want to transfer it to my django server, but for some reason the file is being saved with content being the string null client.js var file = new File([recorder.blob], "rec.webm") var fdata = new FormData() fdata.append('rec.webm',file,'rec.webm') let response = fetch("/recording/", { method: "post", body: fdata, headers: { "X-CSRFToken": csrftoken }, }) server_endpoint if request.method == 'POST': recording = request.FILES.get('rec.webm') print(request.FILES) with open('./rec.webm', 'wb+') as destination: for chunk in recording.chunks(): destination.write(chunk) return HttpResponse("202") return HttpResponseBadRequest rec.webm null -
How to change the datatype of Django model field
I have a set of django models as follows class FirstCategory(models.Model): first_category = models.CharField(max_length=200) def __str__(self): return self.first_category class SecondCategory(models.Model): first_category = models.ForeignKey(FirstCategory, on_delete=models.CASCADE) second_category = models.CharField(max_length=200) def __str__(self): return self.second_category class ThirdCategory(models.Model): first_category = models.ForeignKey(FirstCategory, on_delete=models.CASCADE) second_category = models.ForeignKey(SecondCategory, on_delete=models.CASCADE) third_category = models.CharField(max_length=200) def __str__(self): return self.third_category class FinalList(models.Model): unique_number = models.BigIntegerField() name = models.CharField(max_length=200) first_category = models.ForeignKey(FirstCategory, on_delete=models.SET_NULL, null=True, db_column="first_category") second_category = models.ForeignKey(SecondCategory, on_delete=models.SET_NULL, null=True, db_column="second_category") third_category = models.ForeignKey(ThirdCategory, on_delete=models.SET_NULL, null=True, db_column="third_category") def __str__(self): return self.name When I migrate the models and check the datatypes of the fields in the FinalList table I get the following column_name | data_type ---------------------------+------------------- third_category | bigint first_category | bigint second_category | bigint unique_number | bigint name | character varying I had specified the first, second, and third categories as Character fields. Why is it being migrated as BigInt? I am trying to implement a chained dropdown in my form. I am following SimpleBetterThanComplex tutorial for this -
Django hosted sites response nothing
My django rest framewrok backend site is hosted in cpanel.Somestimes it responses with data and sometimes it responds nothing like in image.Server log doesn't shows any problem.This problems occurs in some interval.It automatically works after some times like 10-15 minutes.What might be the problem? -
Django models: Query to Get the data from the table an hourly basis
enter image description here I am working in Django and python. I have the data for minutes basis in my database please have a look at the image, But when am querying it I want to have a query which fetches the data on an hourly basis Table Name: TrafficTrend_SDP_BHCA This image has the table name and the columns it has. I have the full length of data fromdate 202109270835 to todate 202109290956 202109270835 is the date hour format. "20210927" is the date, "08" is an hour and "35" is minutes. From this table I want to fetch data on an hourly basis. Example: data started with 202109270835 , so i want to get the data something like for 08 hours and 09 hours (an hourly basis). and for each hour the respective columns(VCS1FI) and (VCS1FI_Fail) values should be summed up individually Output could be for 2021092708 hours VCS1FI= "", VCS1FI_Fail="" and for 2021092709 hours VCS1FI= "", VCS1FI_Fail="". -
media image is not able to display on webpage
when click on "yo" I am able to see media file but when tried to display image through the image tag it is not seen on webpage <a href="{{status.adv.url }}">yo</a> <img src="{{status.adv.url}}" width="250" height="250" alt="advertise"/> -
Django sql server migration not working Error: NotImplementedError: the backend doesn't support altering from/to AutoField
NotImplementedError: the backend doesn't support altering from/to AutoField. -
I am getting "not NULL Constraint error" in my unit test only
I need help. My registration system is working perfectly fine when I run on a local server, but when I run my test. It fails. I don't understand why? I am unable to figure out what is wrong, I have deleted the entire database and migrations. even I created the new app and did everything there. But still, I am getting this error. My test_setup.py from rest_framework.test import APITestCase from django.urls import reverse class TestSetup(APITestCase): def setUp(self): self.register_url = '/register/' self.user_data = {"Username":"frontend123", "First name":"Frontend", "Last name":"Developer", "Password":"bitspro##1", "Confirm password":"bitspro##1","Email":"rida@bitspro.com","Date of birth":"1997-12-27"} return super().setUp() def tearDown(self): return super().tearDown() My testViews.py from authentication.models import User from authentication.tests.test_setup import TestSetup class TestViews(TestSetup): def test_user_cannot_register_without_any_data(self): res = self.client.post(self.register_url) self.assertEqual(res.status_code, 400) def test_user_can_register_correctly(self): res = self.client.post(self.register_url, self.user_data, format="json") self.assertEqual(res.status_code, 201) My view.py (I am testing registration system only from rest_framework.response import Response from rest_framework.views import APIView from authentication.models import User as Client class Register(APIView): def post(self, request): username = request.data.get('Username') first_name = request.data.get('First name') last_name = request.data.get('Last name') password = request.data.get('Password') confirm_password = request.data.get('Confirm password') date_of_birth = request.data.get('Date of birth') email = request.data.get('Email') if password == confirm_password: if Client.objects.filter(username = username).exists(): return Response({"message": "this username already exist"}, 400) elif Client.objects.filter(email = email).exists(): return Response({"message": … -
How to represent all ManyToMany fields in djangorestgramework serializer class?
I want to render ManyToMany fields with there values using django. Base model class SalesAction(models.Model): sales_representative = models.ForeignKey( SalesRepresentative, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) remark = models.CharField(max_length=500) date = models.DateField() medicines = models.ManyToManyField(Medicine, through='SalesActionMedicine') def __str__(self): return f'{self.sales_representative} - {self.doctor}' Details model class SalesActionMedicine(models.Model): sales_action = models.ForeignKey(SalesAction, on_delete=models.CASCADE) medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE) quantity_type = models.CharField(max_length=50) quantity = models.PositiveIntegerField() What I want is to represent all medicines related to each object in the SalesAction model class. This is the serializer I built. class SalesActionMedicineSerializer(serializers.ModelSerializer): class Meta: model = SalesActionMedicine fields = ('sales_action', 'medicine', 'quantity_type', 'quantity') class SalesActionSerializer(serializers.ModelSerializer): medicines = SalesActionMedicineSerializer(many=True) class Meta: model = SalesAction fields = ('sales_representative', 'doctor', 'remark', 'date', 'medicines') This code gives my this error: Got AttributeError when attempting to get a value for fieldsales_actionon serializerSalesActionMedicineSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Medicineinstance. Original exception text was: 'Medicine' object has no attribute 'sales_action'. -
Django Reportlab getKeepWithNext
I am trying to add an image to a PDF generated in Reportlab. I am trying to access the image from a Django field, specifying the full path of the file. When I run the below code I get: "Exception Value: getKeepWithNext". Any help as to what I am doing wrong would be greatly appreciated. def holding_pdf(self, course_slug, holding_slug): buffer = io.BytesIO() holding = HoldingDetail.objects.get(identifier=holding_slug) doc = SimpleDocTemplate(buffer, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=72, pagesize=A4, title=f"Why the {holding.name} is in the portfolio.pdf") elements = [] styles = getSampleStyleSheet() elements.append(Paragraph(str(holding.logo.path), styles['Normal'])) elements.append(Image(holding.logo.path)) print(holding.logo.path) doc.build(elements) buffer.seek(0) return FileResponse(buffer, as_attachment=False, filename=f"Why the {holding.name} is in the portfolio.pdf") -
How to change the executer of python in vscode?
I was trying to change the executer of python in vscode. I have installed python3 in my system.However default executer of python in vscode is python.So i am getting error as 'python not found' whenever i try to run code. So how could i change the executer to python3 in line no 4066? -
OperationalError at /users/friend-request/accept/6/ no such table: main.users_profile__old
I'm unable to accept the friend request, delete request and send request is working fine users/views.py @login_required def send_friend_request(request, id): user = get_object_or_404(User, id=id) frequest, created = FriendRequest.objects.get_or_create( from_user=request.user, to_user=user) return HttpResponseRedirect('/users/{}'.format(user.profile.slug)) @login_required def accept_friend_request(request, id): from_user = get_object_or_404(User, id=id) frequest = FriendRequest.objects.filter(from_user=from_user, to_user=request.user).first() user1 = frequest.to_user user2 = from_user user1.profile.friends.add(user2.profile) user2.profile.friends.add(user1.profile) if FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first(): request_rev = FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first() request_rev.delete() frequest.delete() return HttpResponseRedirect('/users/{}'.format(request.user.profile.slug)) if any more code is required, please comment below -
How to add a button in a django list to add List's data to a HTML TextField?
I'm looking for the best implementation of adding data to view from the Django model in a list rendered in a template with the help of a button that sits along with other data on every row. To be specific, I want a person's phone number to be selected and be initiated to view on form submission which then sends SMS to those numbers via API. models.py class Patient(models.Model): patient_serial = models.IntegerField(null=True, blank=True) customer = models.CharField(max_length=100) phone_regex = RegexValidator( regex=r'^\+?1?\d{9,10}$', message="Phone number must be entered in the format: '98xxxxxxxx'. Up to 10 digits allowed.") customer_phone = models.CharField( validators=[phone_regex], max_length=10, blank=True) GENDER_CHOICES = ( ('O', 'Others'), ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField( max_length=10, choices=GENDER_CHOICES, default='None') date_of_birth = models.DateField() age = models.IntegerField(null=True, blank=True) billing_address = models.CharField(max_length=100, null=True, blank=True) date = models.DateField()blank=True) issue_detail = models.TextField( max_length=250, null=True, default="", blank=True) treatment_plan = models.ForeignKey( TreatmentPlan, on_delete=models.CASCADE, null=True, blank=True) total_amount = models.ForeignKey( Invoice, on_delete=models.CASCADE, blank=True, null=True) status = models.BooleanField(default=False) def __str__(self): return str(self.customer) def get_status(self): return self.status def get_absolute_url(self): return reverse('patients') def num(self): return self.customer_phone views.py def composeSMS(request): text = request.POST.get('smsArea', False) recipients = request.POST.get('contacts', False) sms = requests.post( "<api-endpoint>", data={'token': '<api-key>', 'from': 'Company', 'to': recipients, 'text': text}) sms_status_code = sms.status_code sms_response = sms.text … -
Django Rest-Framework with simpleJWT returns Anonymous User when sending request from Postman
I am trying to use SimplejWT along with Django Rest-Framework to do the authentication. When I go to the endpoint through the browser, I get this response: But when I use postman, I get back an anonymous user. This is my postman config: My SimpleJWT config is: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=30), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } The code for the endpoint is: @api_view(['GET']) def get_user_profile(request): print(request.user) user= request.user serializer= UserSerializer(user, many= False) return Response(serializer.data) The user serializer is coded this way: class UserSerializer(serializers.ModelSerializer): class Meta: model= User fields= ['id', 'username', 'email'] -
Filter based on whether a user is part of a project's team
I have two models Project and User. A project's team is a many to many field with with the User model. models.py # Create your models here. class Project(models.Model): title = CharField(max_length=30) description = TextField() due_date = DateField() team = ManyToManyField(settings.AUTH_USER_MODEL) INACTIVE = 0 ACTIVE = 1 STATUS = ( (INACTIVE, ('Inactive')), (ACTIVE, ('Active')), ) active = models.IntegerField(default=1, choices=STATUS) def __str__(self) -> str: return f'{self.title}' views.py @login_required def index(request): user = request.user tickets = Ticket.objects.filter(assigned_to=user) ticket_count = len(tickets) projects = Project.objects.filter(team__in = user) project_count = len(projects) context = { 'tickets':tickets, 'ticket_count':ticket_count, 'projects':projects, 'project_count':project_count, } return render(request, 'bugtracker_app/index.html', context) I am trying to use the Query set API to return the projects a the currently logged on user has been assigned to. However I've been getting the following error: TypeError: 'User' object is not iterable How can I resolve this error and get a query set of the projects a user is working on? -
Is there a standard practice for storing flat data files that are used for testing in a Django project?
I'm unit testing the way that my Django application loads and processes various flat files and I'm having trouble deciding where to store the files that contain the data for these tests. Is there a standard practice or location for this? Would it make more sense to store these files in one of the STATICFILES_DIRS or in a subdirectory of MEDIA_ROOT, or some other directory? If some other directory, how might that be configured in the settings module? For example: from pathlib import Path from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase def simulate_uploaded_file(data_path: Path, filename: str) content_type = get_content_type(filename) filepath = data_path / filename content = open(filepath, 'rb').read() data_file = SimpleUploadedFile(data_file_path, content, content_type) class TestFileHandler(TestCase): @classmethod def setUpTestData(cls): test_data_path: Path = settings.TEST_DATA_DIR # <- IS THERE A STANDARD LOCATION FOR THIS? cls.valid_csv: SimpleUploadedFile = simulate_uploaded_data(test_data_path, 'filename.csv') -
INSERT, REPLACE, UPDATE not working in Python and SQLite with Django Framework
What I am using I am using python codes to access a database with multiple tables in SQLite. All this is done in Linux's Ubuntu OS The Problem The problem is that I am unable to UPDATE, INSERT, REPLACE data in one of the tables through python codes but DELETE works just fine, meaning I am able to delete a specific row in the table. For reference, when using the same commands for another table, it works fine. What I have done I have used .commit() in python, but the codes do not commit. To see if these commands work in the database itself, in case there were unknown permissions set, I used DB Browser for SQLite and they do work when done directly through the database. Any idea if there might be any explicit permissions set to each command in SQLite or is there any other cause for this? And are there any suggestions as to what I should do to check? -
Django - Test to ping DRF Swagger
I have these urls under my urls.py SWAGGER_URLS = [url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='swagger')] then I have this test SwaggerTest.py from django.test import TestCase from django.urls import reverse from rest_framework import status class SwaggerTest(TestCase): def test_successful_swagger_pint(self): response = self.client.get(reverse('swagger')) self.assertEqual(response.status_code, status.HTTP_200_OK) I'm getting the exception django.urls.exceptions.NoReverseMatch: Reverse for 'swagger' not found. 'swagger' is not a valid view function or pattern name. when I run this test. When I ping the url myself it works fine. I'm using django-rest-swagger==2.2.0. -
DoesNotExist at /nuevo/ Profile matching query does not exist
sorry I'm quite new to Django and Python, doing a school project, I was doing a default login with python, it creates the users and makes a login, so far so good. When I log in with the admin I can enter "html.html" without problems and the view runs and makes the queries in the database, the problem is when I log in with a different profile than the admin, I get this message DoesNotExist at /nuevo/ Profile matching query does not exist. Request Method: GET I think the problem is with this query query = Profile.objects.get(pk=request.user.pk) What I wanted was for the user who is logged in to send me to work on their database, I don't know what else to do :( these are my models from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='batman.png') equip = models.CharField(max_length=1500,default=0) pokemon1 = models.CharField(max_length=1500,default=0) pokemon2 = models.CharField(max_length=1500,default=0) pokemon3 = models.CharField(max_length=1500,default=0) pokemon4 = models.CharField(max_length=1500,default=0) pokemon5 = models.CharField(max_length=1500,default=0) pokemon6 = models.CharField(max_length=1500,default=0) def __str__(self) -> str: return f'Perfil de {self.user.username}' class Post(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE,related_name='posts') timestamp = models.DateTimeField(default=timezone.now) content = models.TextField() class Meta: ordering = ['-timestamp'] def __str__(self): … -
Django UpdateView didn't update page
My form: class TestCaseUpdateForm(forms.ModelForm): class Meta: model = TestCase fields = ( 'name', 'executable', 'parameter_list', 'executable_type', 'test_type' , 'project_name', 'created_by') My views: class EditCaseView(UpdateView): model = TestCase form_class = TestCaseUpdateForm template_name_suffix = '_update_form' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs.get(self.pk_url_kwarg) queryset = self.get_queryset().filter(pk=pk) case = queryset.get() context['my_case'] = case context['my_exetype'] = TestCase.EXECUTABLE_TYPE_CHOICES context['my_ttype'] = TestCase.TEST_TYPE_CHOICES context['projnames'] = PROJNAME_CHOICES return context def get_success_url(self): print("get_success_url") return reverse("integratedTest:testCase") My model: PROJNAME_CHOICES = ( ('Name1', 'Name1'), ('Name2','Name2'), ('Name3','Name3') ) class TestCase(models.Model): EXECUTABLE_TYPE_CHOICES = ( ('e_type1', 'e_type1'), ('e_type2', 'e_type2'), ('e_type3', 'e_type3'), ) TEST_TYPE_CHOICES = ( ('t_type1', 't_type1'), ('t_type2','t_type2'), ('others', 'others'), ) name = models.CharField(max_length=200, unique=True) executable = models.CharField(max_length=1023) parameter_list = models.TextField(blank=True, default = "") project_name = models.CharField(max_length=200, choices = PROJNAME_CHOICES, default="Name1") executable_type = models.CharField(max_length=200, choices = EXECUTABLE_TYPE_CHOICES, default = "e_type1") test_type = models.CharField(max_length=200, choices = TEST_TYPE_CHOICES, default = "t_type1") created_by = models.CharField(max_length=200, default = "sb") create_datetime = models.DateTimeField("testcase created on", auto_now = True) My template: <form method="post">{% csrf_token %} <h1 >Edit Test Case:</h1> <table> <tr> <th>Name:</th> <th>executable:</th> <th>parameter_list:</th> </tr> <tr> <td><input type="text" id="id_name" name="name" value = "{{my_case.name}}" placeholder="short_unique_string" required> </td> <td> <input type="text" id="id_executable" name="executable" value = "{{my_case.executable}}" placeholder="FilenameWithoutPath.py" required> </td> <td><textarea id="id_parameter_list" name="parameter_list" value = "{{my_case.parameter_list}}" placeholder="Copy your parameter string here directly"></textarea> … -
Join 2 tables over 2 columns in django
I have a database imported from mysql in models.py like : class Sig(models.Model): id = models.IntegerField(db_column='Id', primary_key=True) proportion = models.FloatField(db_column='Prop', blank=True, null=True) marine_area = models.CharField(db_column='Marine_Area', max_length=255, blank=True, null=True) habitat = models.CharField(db_column='Habitat', max_length=255, blank=True, null=True) This one doesn't have any coordinates associated. The coordinates are in another table : class Coord(models.Model): id = models.IntegerField(db_column='Id', primary_key=True) marine_area = models.CharField(db_column='Marine_Area', max_length=255, blank=True, null=True) habitat = models.CharField(db_column='Habitat', max_length=255, blank=True, null=True) latitude = models.FloatField(db_column='Latitude', blank=True, null=True) longitude = models.FloatField(db_column='Longitude', blank=True, null=True) I want to visualized my proportions according to their coordinates (latitude and longitude). However, each localisation is define with a marine area and an habitat (each marine area has 3 habitats) for ex So how can I create a new column with the concatenation of marine area and habitat to be able to join my two tables ? or is there any other solution to join my two tables ? Thanks ! -
some css code wont work on django project
I'm having this unusual issue with my CSS file and Django, some of my CSS code will work but some wont and to make it work I have to make a style section on my head tag while the rest of the CSS code is in my style.css file this is really bizarre and only happens with any new code I add to the CSS file. is anyone having the same issue, I have my settings file good and all STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) it is so funny well I'll leave this one odd issue to the pros lol. -
Django Ckeditor Automatically Save Data to Server / Backend
How would I go about automatically saving data from frontend ckeditor to the backend without reloading the page. I tried using ajax to make this work, but I am unable to send the updated content to the backend. Additionally, the javascript on change method is triggering 2x per single input. For example if I type "A" for a new input in ckeditor, it'll trigger twice for some unknown reason. Approach 1 - HTML / JS (Click "submit" button when change is detected) <form class="pt-2" action="#" method="POST" id="designer-form"> {% csrf_token %} {{ form.media }} {% for field in form %} {{ field }} {% endfor %} <div class="mt-4 flex justify-end space-x-4"> <button type="submit" id="submit"> Save Changes </button> </div> </form> <script> CKEDITOR.on('instanceCreated', function(event) { let editor = event.editor; editor.on('change', function() { setTimeout(function () { document.getElementById("submit").click(); }, 2500); }); }); </script> Approach 2 - HTML / JS (Serialize Data) <form class="pt-2" action="#" method="POST" id="designer-form"> {% csrf_token %} {{ form.media }} {% for field in form %} {{ field }} {% endfor %} <div class="mt-4 flex justify-end space-x-4"> <button type="submit" id="submit"> Save Changes </button> </div> </form> <script> CKEDITOR.on('instanceCreated', function(event) { let editor = event.editor; editor.on('change', function() { let data = editor.getData(); setTimeout(function (){ $.ajax({ …