Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test LAMP stack application performance using Codespeed?
We are planning to use Codespeed ( https://github.com/tobami/codespeed ) for analysing and monitoring code of LAMP stack web application (Linux,Apache,MySQL, PHP). Went through documentation, but I couldn't find any reference for using it for LAMP application. Where are we supposed to do linking of Codespeed with our application? Or in which folder our application needs to be placed? -
How do I revoke JWT everytime a new token generated using django-graphql-jwt?
I am using django-graphql-jwt (https://django-graphql-jwt.domake.io/en/latest/index.html) to handle authentication for my Django Python Graphene application. Currently, everytime a new JWT generated, the previous JWT is still active as long as it does not pass its expiry time. I want to revoke/prevent access to previously generated JWT (even if the JWT is not expired yet) whenever I generate a new JWT. What I am thinking is utilizing the origIat inside the JWT payload and comparing it with something like a last_login attribute from the User model. I noticed though, that User.last_login is not updated whenever I am authenticating using JWT. Still finding how to do this problem properly and wondering if there is any of you already solving this problem before. Thanks! -
Can't see removal flags
Django 3.0.8 django-comments-xtd==2.6.2 I'm studyint this section of the tutorial: https://django-comments-xtd.readthedocs.io/en/latest/tutorial.html#removal-suggestion post_detail.html {% extends "base.html" %} {% load comments %} {% load comments_xtd %} {% block title %}{{ object.title }}{% endblock %} {% block content %} <div class="pb-3"> <h1 class="text-center">{{ object.title }}</h1> <p class="small text-center">{{ object.publish|date:"l, j F Y" }}</p> </div> <div> {{ object.body|linebreaks }} </div> {% get_comment_count for object as comment_count %} <div class="py-4 text-center"> <a href="{% url 'blog:post-list' %}">Back to the post list</a> &nbsp;&sdot;&nbsp; {{ comment_count }} comment{{ comment_count|pluralize }} ha{{ comment_count|pluralize:"s,ve" }} been posted. </div> {% if object.allow_comments %} <div class="card card-block mb-5"> <div class="card-body"> <h4 class="card-title text-center pb-3">Post your comment</h4> {% render_comment_form for object %} </div> </div> {% endif %} {% if comment_count %} <ul class="media-list"> {% render_xtdcomment_tree for object allow_flagging allow_feedback %} </ul> {% endif %} {% endblock %} settings.py COMMENTS_XTD_APP_MODEL_OPTIONS = { 'blog.post': { 'allow_flagging': True, 'allow_feedback': False, 'show_feedback': False, } } Problem I have loged in. But I can't see any flag at the right side of every comment’s header. Could you give me a hint where the problem may be hiding? -
Django not creating a testdatabase when testing
I am running tests in my newly created Django project. Normally I would expect to see a test database created for when tests are running. All tests are running fine, but I am seeing that my local database (for runserver use) is beeing used when running the tests. A lot of excess data is beeing created in the wrong database. How can I get my test setup to use the normal test_dabasename setup again? Im not sure what I have changed to make this happen and am totally stumped. -
Django how to correctly acces the context variable in javascript
My question is similar to the these previous questions, however I can't seem to make my code work: How can I pass my context variables to a javascript file in Django? How to use the context variables passed from Django in javascript? I have a list of lists, containing data of the form: data = [[1, 2, 3, 4, ...] [210, 346, 331, 402, ...] [...] ...] where the first list represents the number of each taken sample. I'm passing this data to my HTML file using a class that looks like: class IndexView_charts(generic.TemplateView): """ IndexView: """ module = 'IndexView' template_name = charts_temp_name #variable for the template data = ##extra code here to fetch data def get_queryset(self): log(self.module, 'get_queryset', file=__file__) return self.data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data'] = self.data return context And in the template, I can access the variable data as follows for example and it shows up on the webpage: <h1> {{data.0}} </h1> now, I'd like to access it in my script. In the same file I have the following code: var chartData = {{ data }}; ... some more code here ... data:chartData[1] but I don't get the charts that I would like. If i … -
"User already exist" Custom Django Authentication Backend
I'm coding a custom django authentication, the code works fine for user creation but when I try to login, it is like if I were signing up again, so there is no way of accessing my user account because every time I try to login, I get an error because a user with that credentials already exist (I'm that user). The output is: <ul class="errorlist"><li>address<ul class="errorlist"><li>User with this Address already exists.</li></ul></li></ul> Models.py: class AppUser(AbstractUser): username = models.TextField(unique=True) address = models.CharField(max_length=34, unique=True) key = models.CharField(max_length=34) def __str__(self): return self.username Forms.py: class NewUserForm(forms.ModelForm): class Meta: model = AppUser fields = ("username", "address", "key") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.address = self.cleaned_data["address"] user.key = self.cleaned_data['key'] if commit: user.save() return user class LoginUserForm(forms.ModelForm): class Meta: model = AppUser fields = ("address", "key") def __init__(self, request=None, *args, **kwargs): self.request = request super().__init__(*args, **kwargs) Backends.py: class AppUserBackend(ModelBackend): def authenticate(self, request, **kwargs): address = kwargs['address'] key = kwargs['key'] try: customer = AppUser.objects.get(address=address) if customer.key == key: return customer.user else: print("Error") except AppUser.DoesNotExist: pass Views.py: def login_request(request): if request.method == 'POST': form = LoginUserForm(request=request, data=request.POST) if form.is_valid(): address = form.cleaned_data.get('address') key = form.cleaned_data.get('key') user = authenticate(request=request, address=address, key=key) if user is not None: login(request, user, backend='main.backends.AppUserBackend') … -
How to make ckeditor image upload simple drag and drop
In CKeditor, I did the RichTextUploadingField and all. Everything working perfectly fine. I can see the Image button in top menu. But it is too confusing for user. Like clicking on image button->upload->select Image->send it to server. It's too much for User. Like I need it very simple image upload in ckeditor. What I want is simple image uploading. Meaning, User friendly like click on Image button and then drag and drop or select image(Browse) and upload. There are many thing like image info, link and advanced which I don't want. Because it confuse my users. Can anyone help me with this? Please. By the way I am using django-ckeditor==5.9.0 -
can I display (django's detailview) on (Bootstrap's Modal view)?
I wanna Open an object details(DetailView) in a Bootstrap Modal dialog(not redirecting to another page) thnx in advance -
how to extract particular data from text file on django
when i click on upload file from front end. i would like to extract data from uploaded file in django views.py demo.txt <p> <table border=3D"1"> <tbody> <tr> <th> ID</th> <th>Action</th> <th>Date/Buyer</th> <th> Due By</th> <th> Title</th> </tr> <tr> <td>1435523</td> <td>MODIFIED</td> <td>07/13/2020 02:50:52 PM EDT</td> <td>07/17/2020 03:00:00 PM EDT</td> <td>test</td> </tr> </tbody> </table> </p> </a>Also, please remember that you have the opportunity= to view on additional in django views im trying to extract data from a textfile,and i want to extract only inside data and save it into database,i dont know what to do can any one help me with this def upload_view(request): if request.method == 'POST': print(request.POST) f=request.FILES['file'].read() print(f) inFile = f outFile = open("result.txt", "w") buffer = [] keepCurrentSet = True for line in inFile: buffer.append(line) if line.startswith("<p>"): # ---- starts a new data set if keepCurrentSet: outFile.write("".join(buffer)) # now reset our state keepCurrentSet = False buffer = [] elif line.startswith("</p>"): keepCurrentSet = True print(buffer) return render(request, 'upload.html') else: return render(request, 'upload.html') -
problem in making the groups using django framework! PLEASE HELP OUT
A user want to make a group so that he is the admin of that groups but he also want that if any other user of the site who is not his friend is interested in his group, can click the join button for joining the group then he should be prompted for the password of the group in order to join the group (password of group is set by admin while creating the group). <-- This is what i want but i am unable to find a way to take the password from group admin and authentication with it for other users for joining the group... PLEASE HELP ME AS I AM NOT PROFESSIONAL IN DJANGO here is my models.py file from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.utils.text import slugify # from accounts.models import User import misaka from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html = models.TextField(editable=False, default='', blank=True) members = models.ManyToManyField(User,through="GroupMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args, **kwargs) def get_absolute_url(self): return … -
AttributeError at /mobile/7/delete/ 'tuple' object has no attribute '_meta'
I am trying to delete an item from my project but it gives error. interestingly it is deleting the item but gives error mention above. views.py: def delete_mobile(request, mobile_id): mobile1 = get_object_or_404(Mobile, pk=mobile_id).delete() form = MobileForm(instance=mobile1) if form.is_valid(): form.delete() return redirect('mobile') return render(request, 'device/delete_mobile.html', {'mobile': mobile1}) delete_mobile.html: {% extends 'device/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <form action="{% url 'delete_mobile' mobile.instance.id %}" method="POST"> {% csrf_token %} <h3>Delete {{ header }}:</h3> {{ mobile|crispy }} <button class="btn btn-success" type="submit">Delete</button> </form> {% endblock %} urls.py: path('mobile/<str:mobile_id>/delete/', views.delete_mobile, name='delete_mobile'), -
Configuring Django Rest Framework Pagination
The docs for Django Rest Framework say that configuring pagination is as simple as adding the default pagination class and size to settings.py and making sure that you are using a GenericAPIView. I am doing both of these things and the pagination is not working for me. GET /domains/example.com/hosts/?page=1 returns a 404 error GET /domains/example.com/hosts?page=1 returns all the results What am I missing here? settings.py REST_FRAMEWORK = { 'COERCE_DECIMAL_TO_STRING': False, # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_RENDERER_CLASSES': DEFAULT_RENDERER_CLASSES, 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } views.py class HostList(generics.ListAPIView): """ List all hosts for a given domain """ host_service = HostService() queryset = Host.objects.all() pagination_class = PageNumberPagination def get(self, request, domain_name, format=None): hosts = self.host_service.find_hosts_by_domain_name(domain_name) if len(hosts) == 0: return Response(status=status.HTTP_404_NOT_FOUND) serializer = HostSerializer(hosts, many=True) return Response(serializer.data) urls.py urlpatterns = [ path('domains/', views.DomainList.as_view()), path('domains/<str:domain_name>', views.DomainDetail.as_view()), path('domains/<str:domain_name>/whois', views.DomainWhoisDetail.as_view()), path('domains/<str:domain_name>/hosts', views.HostList.as_view()) ] serializers.py class HostSerializer(serializers.Serializer): created = serializers.DateTimeField() last_updated = serializers.DateTimeField() name = serializers.CharField(); -
Vscode does not read the css after restart
I'm student of programming and i just started working at yesterday on vscode. I'm trying to make a social/house rent platform by using django/jquerry. I made some html, css, js pages, there is a no problem about this, everything okay and working.. then i slept and today just turned on my pc but vscode didn't read the css files (not sure about js files too). I use href="{% static 'polls/style.css'}" method for calling static files I tried everything but it's still wasn't reading the current files. So i did <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> to //the only difference is name of the css file <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> and renamed my stlye.css file to styles.css and bang it's working... I thought it was a one time bug but it's not. Before 15 min ago i put my computer to sleep mode and when i came back i solved the same problem the same way.. does anyone have this problem and how can i fix it ? -
Dynamically add inline formset in django using javascript
I have modelform called WorkExperienceForm. Currently the form is adding only one information. I want to convert it in formset. forms.py: class WorkExperienceForm(forms.ModelForm): """ Creates a form for saving employee work experiences """ class Meta: model = WorkExperience fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ] widgets = { 'previous_company_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'job_designation': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'from_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal3'}, format='%m/%d/%Y'), 'to_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal4'}, format='%m/%d/%Y'), 'job_description': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) I want to add a "Add" button to the frontend. When user presses add button, same form will be generated. This can be done unlimited times. Any help will be appreciated. -
Django filter is not working with a field having + value
I have a field in my models as: cl_name Whenever i try to filter any queryset : def get_queryset(self): cl_name = self.request.query_params.get('cl_name', None) //somecode queryset = queryset.filter(cl_name=cl_name) Whenever cl_name has lorem+ipsun ,filter is not working but it's working fine if there's no + sign. -
pass argumant in url without clean other argumant in django and js
i use Paginator django and when i click on pages button. url changes to this : /admin/orders/?page=2 now i want to set status in url arguments like this : /admin/orders/?status=1. it works! but in this case when i change page , status parameter is cleaned! i want to set both of parameter in url like this : /admin/orders/?status=1&page=2 how can i solve this problem with js? this is my paginator code : if request.method == "GET": orders = get_orders(request.GET) orders = Paginator(orders,5) page = request.GET.get('page') if page is None : page = 1 order_list = orders.page(page) print(len(orders.page_range)) index = order_list.number - 1 max_index = len(orders.page_range) start_index = index - 3 if index >= 3 else 0 end_index = index + 3 if index <= max_index - 3 else max_index page_range = list(orders.page_range)[start_index:end_index] for o in order_list: o.product.name = get_product_name(o.product) statuses = Status.objects.all() context = { 'orders' : order_list, 'page_range' : page_range, 'statuses' : statuses } return render(request,'staff/orders/products.html',context) and this is my paginator section in html template : {%if orders.has_previous%} <li class="page-item"> <a class="page-link" href="?page={{orders.previous_page_number}}" tabindex="-1">قبلی</a> </li> {%else%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">قبلی</a> </li> {%endif%} {% for pg in page_range %} {% if blogs.number == pg %} <li class="page-item … -
Why function to_excel of Pandas lowercases the formulas string?
thank you for helping me. I'm trying to write an excel from a pandas.DataFrame using function .to_excel(). It's everything ok, but the issues is that something happen to the formulas I have in the dataframe, I show you what: for indx in range(len(currency)): if currency[indx] in list_currencies: row = str(list_currencies.index(currency[indx]) + 2) c_2019 = '=%s*$Currency.%s%s'%(str(gt_2019_mzero[indx]), index_excel['2019'], row) c_2020 = '=%s*$Currency.%s%s'%(str(gt_2020_mzero[indx]), index_excel['2020'], row) c_2021 = '=%s*$Currency.%s%s'%(str(gt_2021_mzero[indx]), index_excel['2021'], row) c_2022 = '=%s*$Currency.%s%s'%(str(gt_2022_mzero[indx]), index_excel['2022'], row) c_2023 = '=%s*$Currency.%s%s'%(str(gt_2023_mzero[indx]), index_excel['2023'], row) gt_2019_toconvert.append(c_2019) gt_2020_toconvert.append(c_2020) gt_2021_toconvert.append(c_2021) gt_2022_toconvert.append(c_2022) gt_2023_toconvert.append(c_2023) ... dataframe_impacts.insert(32, 'inde_2019 >= 0 €', gt_2019_toconvert) dataframe_impacts.insert(33, 'inde_2020 >= 0 €', gt_2020_toconvert) dataframe_impacts.insert(34, 'inde_2021 >= 0 €', gt_2021_toconvert) dataframe_impacts.insert(35, 'inde_2022 >= 0 €', gt_2022_toconvert) dataframe_impacts.insert(36, 'inde_2023 >= 0 €', gt_2023_toconvert) Then, in the view: # Create a Pandas Excel writer using XlsxWriter as the engine. options = {} options['strings_to_formulas'] = True writer = pd.ExcelWriter(excel_path, engine='openpyxl', options=options) # Write on excel: impacts.to_excel(writer, sheet_name='Impacts', index=False) currencies_table.to_excel(writer, sheet_name='Currency', index=True) So, for example c_2019 should be --> c_2019 = "=500*$Currency.C3" ( is value*%SHEET_NAME.CELL_COORDINATES) But what I actually get inside the excel file in the cell is "=500*&currency.c3", all letters in lowercase making the formulas does not working at all. Can anyone help me to figure it out? I'm using: Python 3.7.8; … -
413 Request Entity Too Large error in Django on AWS
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I need to get .igs file in one of my forms but I'm getting 413 Request Entity Too Large error. I have tried the solution below and it's combinations but they didn't work. .ebextensions/nginx-file-fize.config container_commands: 01_reload_nginx: command: "sudo service nginx reload" files: "/etc/nginx/conf.d/proxy.conf" : mode: "000644" owner: root group: root content: | client_max_body_size 25M; How can I fix this issue? -
Query based on ManytoMany Field Django
I have the following models on which I want to query based on ManytoMany Field: class Topping(models.Model): topping_name=models.CharField(max_length=16) class Cart_Item(models.Model): pizza=models.ForeignKey(Pizza, blank=True, null=True, on_delete=models.CASCADE) toppings=models.ManyToManyField(Topping, blank=True) quantity=models.IntegerField() I have a list of toppings available with me. I want to query a Cart_Item where toppings field contains all the values in the list. For example if my list is toppings_list=["Pepperoni","Mushroom"], then I want the Cart_Item where toppings contains only these 2 toppings. How can I query like that? -
xlwt showing date differently
i am trying to generate a excel file from model in django but the date comes different how do i change it. i tried num_format_str but it changes everything to date import xlwt def excelfilegenerator(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="users.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('details') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['DATE', 'UNIT', 'Blowroom', 'Waste_collection','Carding','Comber_and_drawing','Speedframe','pre_total','Spg_db1','Spg_db2', 'Spg_db3','Spg_db4','Spg_total','Autoconner','Post_Spinning_Total','Pre_HMD','Spg1_HMD','Spg2_HMD','Post_spg_HMD','Total', 'Compressor','Lightning','Total_units','Production','U_K_G','Con_pro_40s','Con_UKG_40s','Compac_con_pro_40s','Compac_con_ukg_40s',] # columns = ['DATE',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() date = xlwt.XFStyle() date.num_format_str = 'dd/mm/yyyy' rows = TableModel.objects.all().values_list('Date','Unit', 'Blowroom', 'Waste_collection','Carding','Comber_and_drawing','Speedframe','pre_total','Spg_db1','Spg_db2', 'Spg_db3','Spg_db4','Spg_total','Autoconner','Post_Spinning_Total','Pre_HMD','Spg1_HMD','Spg2_HMD','Post_spg_HMD','Total', 'Compressor','Lightning','Total_units','Production','U_K_G','Con_pro_40s','Con_UKG_40s','Compac_con_pro_40s','Compac_con_ukg_40s') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response -
How to display only the allowed foreign key values on the form in django?
I have four models class Courses(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=254) assigned_teacher=models.ForeignKey('users.Teacher',null=True,blank=True,on_delete=models.SET_NULL) price=models.DecimalField(max_digits=6,decimal_places=2) class Section(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=254) course=models.ForeignKey(Courses,on_delete=models.CASCADE) class Video(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=254) url=models.URLField(max_length=200) section=models.ForeignKey(Section,on_delete=models.CASCADE) course=models.ForeignKey(Courses,on_delete=models.CASCADE) class Teacher(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) bought_course=models.ManyToManyField(Courses) I am making a video creation form that has the foreign key section. Now, I want the course foreign key to only display the courses that have been assigned to the teacher and further show the sections available in the course selected. Any suggestions on how to proceed with this? I am working in Django. -
GUnicorn not showing up locally, not using any ports (Django)
I am trying to run a Docker container via the command: docker run --rm -d projectname:latest And I get the following gunicorn lines: [2020-07-28 11:56:50 +0000] [10] [INFO] Listening at: http://127.0.0.1:8000 (10) [2020-07-28 11:56:50 +0000] [10] [INFO] Using worker: sync [2020-07-28 11:56:50 +0000] [12] [INFO] Booting worker with pid: 12 From this I thought it was working fine. However, nothing is showing up in 127.0.0.1:8000. After using Network Utility's port scanner, no ports above or including 8000 are being used. When I right click on the container in Visual Studio Code (with Docker extension installed) and click 'Open in Browser' it states "No valid ports are available. Source: Docker (Extension)". How can I see the app running locally? What could the issue possibly be? -
DjangoCMS Getting Authors and Their Article Counts Efficiently
I am currently trying to setup a plugin for a site running DjangoCMS. This plugin does something quite similar to what some plugins in AldrynNewsBlog do. However, there will be some differences. Basically, there are authors and they have articles, videos and other content on the site. The plugin will serve the page that contains thumbnails of all these authors and a summary of content for each author. This is the plugin code: class AuthorsPlugin(NewsBlogAuthorsPlugin): """ We are modeling this plugin after AldrynNewsBlog Authors plugin. It is a good start, and there will be some diveregences in functionality. """ label = models.CharField(_("Plugin Name"), max_length=200) draft_id = models.IntegerField(null=True, blank=True) authors = models.ManyToManyField(CommonModels.AuthorProfile, related_name="authors_list_plugin") def copy_relations(self, oldinstance): #self.mentors = oldinstance.mentors for author in oldinstance.authors.all(): self.authors.add(author) author.save() def get_authors_and_article_counts(self, authors): """stub for future method returning authors and their article counts""" # first set up getting the article count subquery = """ SELECT COUNT(*) FROM aldryn_newsblog_article WHERE aldryn_newsblog_article.author_id = aldryn_people_person.id AND aldryn_newsblog_article.app_config_id = %d""" #limit subquery to published articles subquery += """ AND aldryn_newsblog_article.is_published %s AND aldryn_newsblog_article.publishing_date <= %s """ % (SQL_IS_TRUE, SQL_NOW_FUNC, ) for author in self.authors: pass Author model is as follows: from aldryn_people.models import Person @python_2_unicode_compatible class AuthorProfile(models.Model): full_name = HTMLField(configuration='CKEDITOR_SETTINGS_TITLE') … -
Why am I getting logs in this order while making ajax call?
I am trying to make ajax call using JQuery in Django but I am not able to get the expected output. Not able to debug even after struggling for hours now I am posting it on stack overflow, Would be glad if you explain me the problem Input var team_with_mentor; var team_without_mentor; var users = []; var mentors; var names = {}; $.ajax({ url: "{% url 'mentor' %}", method : 'GET', dataType: 'json', success: function (data) { mentors = data; // console.log(mentors); } }).then(() => { for(let i=0; i<mentors.length; i++){ get_name(mentors[i].id) } }).then(() => { console.log(mentors); for(let i=0; i<mentors.length; i++){ let name = names[mentors[i].id] console.log("name1", names); $('.selector').append(`<option class='p-3' key=${mentors[i].id}>${name}</option>`); } }) async function get_name(id) { await $.ajax({ url: "{% url 'mentor' %}", method : 'GET', data: { "id": id }, dataType: 'json', success: function (data) { // console.log(data.mentor) names[id] = data.mentor console.log("name2", names); } }) } Output name1 {} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} please help me to understant what's happening behind the seen Doubt: Why it's not waiting for the second .then() block to finish before … -
How to fix playback error or get playback in Django?
I am trying to add a player in admin admin.py class Admin(admin.ModelAdmin): readonly_fields = ('player',) def player(self, obj): template = f'<audio controls>' \ f' <source src="{{obj.get_url()}}"> ' \ f'</audio>' #template = f'<audio src="obj.get_url()" controls></audio>' return mark_safe(template) Method get_url contain in some model: def get_url(self): return self.sound.url If I use commented template, I get an error: If I use uncommented template, music doesn't playback: