Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: session key doesn't works in CORS?
I want to create a object(Cart) with user session_key. models.py: class Cart(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) session_key = models.CharField(max_length=200, blank=True) product = models.ManyToManyField(Product, related_name='product_items', blank=True) views.py: @api_view(['GET']) def addToCart(request, pk): product = Product.objects.get(id=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'added'}) urls.py: path('addToCart/<str:pk>/', views.addToCart, name='addToCart'), if I go to this url directly from my browser search bar, session key works fine. But if I want to access this url from React app it doesn't work. It shows server error. django.db.utils.IntegrityError: null value in column "session_key" of relation "e_commerce_cart" violates not-null constraint DETAIL: Failing row contains (54, null, null) In front-end, I've made a button, it will call addToCart function. Reactjs: addToCart=()=>{ var id = this.props.id var url2 = 'http://127.0.0.1:8000/addToCart/'+id+'/' fetch(url2,{ method:'GET', headers: { 'Content-Type': 'application/json', } }).then(res=>res.json().then(result=>{ if(result.response === 'added'){ //do something } })) } I'm using localhost for both front-end and back-end. I also want to add that, if I do like this⬇️ def addToCart(request, pk): if not request.session.session_key: request.session.save() product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) print(request.session.session_key) #it print different session_key for same user (every time user call this function) return Response({'response':'ok'}) when this function is called (by clicking that button from … -
Django import_export Imported file has a wrong encoding: 'charmap' codec can't decode byte
I'm using django's import_export lib. But when I'm importing my json file I'm receiving the following error Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x81 in position 1602: character maps to I've found similar questions but they don't conver django import_export. My json file contains arabic caracters and ascii caracters. Here's a json object from it : {"id":"35","code":"35","name_fr":"Boumerd\u00e8s","name_ar":"بومرداس"} Here's my import_export class where I'm precising utf-8 encoding class SpecAdmin(ImportExportActionModelAdmin): from_encoding = 'utf-8' def get_instance(self, instance_loader, row): try: params = {} for key in instance_loader.resource.get_import_id_fields(): field = instance_loader.resource.fields[key] params[field.attribute] = field.clean(row) return self.get_queryset().get(**params) except Exception: return None If anyone had a similar problem with this library can you please tell me what I'm doing wrong. -
Not being able to remove virtual environment using command 'pipenv --rm'
I'm trying to use requests package in my django project. I've installed pipenv using the following command pip install pipenv And I installed requests by using the command pipenv install requests as (myEnv) C:\Users\dell\PycharmProjects\WeatherApp\weather>pipenv install requests Creating a virtualenv for this project... Pipfile: C:\Users\dell\PycharmProjects\WeatherApp\weather\Pipfile Using C:/Users/dell/AppData/Local/Programs/Python/Python39/python.exe (3.9.4) to create virtualenv... [=== ] Creating virtual environment...created virtual environment CPython3.9.4.final.0-64 in 5997ms creator CPython3Windows(dest=C:\Users\dell\.virtualenvs\weather-5a5okUMG, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\dell\AppData\Local\pypa\virtualenv) added seed packages: pip==21.1.2, setuptools==57.0.0, wheel==0.36.2 activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator Successfully created virtual environment! Virtualenv location: C:\Users\dell\.virtualenvs\weather-5a5okUMG Creating a Pipfile for this project... Installing requests... Adding requests to Pipfile's [packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Locking...Building requirements... Resolving dependencies... Success! Updated Pipfile.lock (fe5a22)! Installing dependencies from Pipfile.lock (fe5a22)... ================================ 0/0 - 00:00:00 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. (myEnv) C:\Users\dell\PycharmProjects\WeatherApp\weather>pipenv install requests Installing requests... Adding requests to Pipfile's [packages]... Installation Succeeded Installing dependencies from Pipfile.lock (fe5a22)... ================================ 0/0 - 00:00:00 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. Then I imported requests package in my views.py file and run my server … -
How can I solve this? 'int' object is not iterable
I'm making an Online shop using Django and trying to add quantity of each product from cart and it throws the error under : 'int' object is not iterable I know that it should be integer in this code(this is my views.py): def minus_cart(request): pnum = request.GET.get("pnum") cart = Order.objects.get(prod_num_id = pnum) cart.save() # save 호출 return redirect( "minus_cart_pro" ) def minus_cart_pro(request): memid = request.session.get( "memid" ) cart = Order.objects.filter(order_id_id = memid) member = Sign.objects.get(user_id = memid) pnum = request.GET.get("pnum") template = loader.get_template("cart_view.html") count = 0 for add in cart : count -= add.quan - 1 context = { "memid":memid, "cart":count, "member":member, "pnum":pnum, } return HttpResponse( template.render( context, request ) ) so I changed like this : count = 0 for add in cart : count -= add.quan - 1 the error shows that I have an error at my last line. return HttpResponse( template.render( context, request ) ) and this is my template : {% if memid %} <li class="nav-item"><a class="nav-link" href="/member/mypage?user_id={{memid}}">MyPage</a></li> <li class="nav-item"><a class="nav-link" href="/member/logout">Logout</a></li> <span class="fw-bolder">{{ memid }} 님 안녕하세요</span> {% endif %} {% if not memid %} <li class="nav-item"><a class="nav-link" href="/member/login">MyPage</a></li> <li class="nav-item"><a class="nav-link" href="/member/login">Login</a></li> {% endif %} how can I solve this? -
Django admin list_editable custom query
I have a model Submission that is shown in the admin of a Django site. class SubmissionAdmin(admin.ModelAdmin): """ Display information about the submission """ model = models.Submission #--> Define model to get info list_display = ( #--> View elements 'id', 'statusStaff', ) list_editable = ['statusStaff'] list_filter = ['statusStaff'] # Filter by statusStaff is a foreign key column referencing the following model: class StatusStaff(models.Model): """ Status of the submission used by the staff members """ #--> Fields name = models.CharField( verbose_name = ('Status'), max_length = 100, unique = True, ) active = models.BooleanField( default = True, ) #--> Meta class Meta: verbose_name = "Submission Status" verbose_name_plural = "Submission Status" #--> Methods def __str__(self): """ """ return self.name #--- #--- Right now the list_editable option leads to all values in StatusStaff being shown in the dropdowns and also in the Filters options. I would like that only entries with active = True are shown in both the dropdown generated with list_editable and in the Filters options. Is there a way to modify the query used to get the values for list_editable and Filters? -
How to represent Geodjango model in a django-leaflet leaflet map?
In my django app I am using Geodjango, django-leaflet and leaflet-ajax. I have a route model with a LineStringField. I want to render that route in a template using a leaflet map. I have tried the following code with other models (those that have a Point field instead). But for any reason this code is not working with the RouteModel. The leaflet map shows nothing. How can I add that route to the "gis" leaflet map Here is the model definition from django.contrib.gis.db import models class RouteModel(models.Model): name = models.CharField(verbose_name=_("Nombre"), max_length=50, blank=False, null=False) route_type_id = models.ForeignKey("RouteTypeModel", verbose_name=_("Tipo"), blank=True, null=True, on_delete=models.SET_NULL, related_name="routes") start_date = models.DateField(verbose_name=_("Fecha inicio")) end_date = models.DateField(verbose_name=_("Fecha fin")) route_geom = models.LineStringField(verbose_name=_("Ruta"), srid=4326) def __str__(self): return self.name class Meta: db_table = 'riesgo_route' managed = True verbose_name = _('Ruta') verbose_name_plural = _('Rutas') Here is the ajax view: @login_required(login_url='/login/') def route_get_location(request,pk): route=serialize('geojson',RouteModel.objects.filter(id=pk)) return HttpResponse(route,content_type='json') urlpatterns = [ # url definitions path('ruta/localizar/<str:pk>', route_get_location, name='route_locate'), ] And in the template: {% leaflet_map "gis" callback="window.our_layers" %} <script type="text/javascript"> function our_layers(map,options){ //var datasets= new L.GeoJSON.AJAX("{% url 'mailapp:polygon_get_location' %}" ,{}); var datasets= new L.GeoJSON.AJAX("{% url 'riesgo:route_locate' route.id %}" ,{}); datasets.addTo(map); } </script> -
Using Django Model: Concatenating Model Fields
This appears easy in my head, but still can't get it done. This is my model, and it's working as I'd like, though I admit it can be better. ''' from django.db import models class Engineers(models.Model): position = ( ('NOC', 'NOC'), ('Supervisor', 'Supervisor'), ('Site Manager','Site Manager'), ('Site Engineer', 'Site Engineer'), ) region = ( ('SS','South-South'),('SW','SW'),('SE','SE'), ('NE','NE'),('NW','NW'),('NC','NC'), ) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) email = models.EmailField(max_length=50) username = models.CharField(max_length=20) phone = models.CharField(max_length=11) position = models.CharField(max_length=20, choices=position) workarea = models.CharField(max_length=20, choices=region) face = models.ImageField(upload_to='', height_field=15, width_field=9, blank=True) ''' So the issue is, instead of asking the user to enter a username, I want the username field to be automatically populated with the firstname.lastname concatenated like firstname + '.' lastname. in the database. How do I get this done? Thank you in anticipation. -
Error when uploading/viewing certain pictures - rendition not found - django storages
Wagtail version: 2.9.2 Django storages: ==1.11.1 Error: 2021-06-07 14:13:12 ERROR Internal Server Error: /admin/images/38/ Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/wagtail/images/models.py", line 300, in get_rendition focal_point_key=cache_key, File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/query.py", line 417, in get self.model._meta.object_name wagtail.images.models.Rendition.DoesNotExist: Rendition matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/query.py", line 559, in get_or_create return self.get(**kwargs), False File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/query.py", line 417, in get self.model._meta.object_name wagtail.images.models.Rendition.DoesNotExist: Rendition matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 163, … -
Best way to do a URL dispatcher for this situation?
I'm really new to django and django rest framework and really need help on how to optimize this. So I have this in my views.py and url.py files. urls.py from . import views from django.urls import path urlpatterns = [ path('api/aapl/',views.aapl.as_view()), path('api/msft/',views.msft.as_view()), path('api/tsla/',views.tsla.as_view()) ] views.py from django.shortcuts import render from rest_framework import generics, viewsets from .models import Stock, priceHistory # Create your views here. from .serializers import StockSerializer, PHSerializer class aapl(generics.ListCreateAPIView): a = Stock.objects.get(ticker='AAPL') queryset = priceHistory.objects.filter(stock = a) serializer_class = PHSerializer class msft(generics.ListCreateAPIView): a = Stock.objects.get(ticker='MSFT') queryset = priceHistory.objects.filter(stock = a) serializer_class = PHSerializer class tsla(generics.ListCreateAPIView): a = Stock.objects.get(ticker='TSLA') queryset = priceHistory.objects.filter(stock = a) serializer_class = PHSerializer As you can see the aapl, msft, tsla views are basically the same thing. I want to make it more efficient and compact by only writing 1 APIView. I want to be able to have a path of path('api/stock/<str:id>',views.generalstock.as_view()) but I tried a few thing but it doesn't seem to work. I don't know how to pass the id to the view and what kind of viewset to use. How would I write out a more compact and general solution in urls.py and views.py? Thank you so much! -
I want to have two foreign key for a model in djano. One of these foreign key must create when something special happens
I want to have two foreign key for a model. One of these foreign key must create when something special happens. How can I write this and call it at a specific time? Can I write it as a function in model and call it in view when something special happens? -
RemovedInDjango20Warning: "Direct assignment to the forward side of a many-to-many set is deprecated" with setattr in the loop
In Django 1.11 I get this warning: RemovedInDjango20Warning: Direct assignment to the forward side of a many-to-many set is deprecated due to the implicit save() that happens. Use categories.set() instead. But it happens inside of the loop in place where we use setattr to add the attribute and assign it with value: for f, v in m2m_fields.items(): setattr(rule, f, v) How to avoid the arising of this warning from this code snippet? -
How to change cursor on chartjs doughnut chart hover?
I have a doughnut chart created with chartjs. I want to chart the mouse cursor to "pointer" when I hover any of the doughnut sections. How do I do that? Here is my code <canvas id="myChart" width="50" height="40"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script type="text/javascript"> const data2 = { labels: {{chart_labels|safe}}, datasets: [{ label: 'My First Dataset', data: {{chart_data|safe}}, backgroundColor: [ 'rgb(54, 162, 235)', 'rgb(255, 99, 132)', ], hoverOffset: 4 }] }; var ctx = $("#myChart").get(0).getContext("2d"); var myChart = new Chart(ctx, { type: 'doughnut', data: data2 }); </script> -
I want to schedule the email send for some choosen date . How can I do that in DRF?
I want to take the receiver email address and schedule date as an input and send mail to the schedule date. I have following lines of code in views.py Actually I'm looking forward to use apscheduler package for async background task in django but any suggestions and solutions are appreciable. class SendMailView(APIView): def post(self, request, *args, **kwargs): ''' POST Method for sending Email ''' send_to = request.data.get('receiver_email') schedule_for = request.data.get('schedule_date') email_plaintext_message = " Hello" send_mail( # title: "Test mail, # message: email_plaintext_message, # from: 'some@gmail.com, # to: [send_to] ) return Response({"status":"Email Send"},status=status.HTTP_200_OK) -
React With Django, Not auto refreshing with npm run dev
I've built React components in Django, but every time I update my react component I have to run npm run dev + reload the browser to see the changes. How can I fix this issue to make react refresh automatically after changes? I have --watch on my script but still doesn't work package.json { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.12.3", "@babel/preset-env": "^7.12.1", "@babel/preset-react": "^7.12.5", "babel-loader": "^8.1.0", "react": "^17.0.1", "react-dom": "^17.0.1", "webpack": "^5.4.0", "webpack-cli": "^4.2.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.12.1", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "react-router-dom": "^5.2.0" } } index.js import App from "./components/App"; App.js import React, {Component} from "react"; import {render} from "react-dom"; import HomePage from "./HomePage"; class App extends Component { constructor(props) { super(props); } render() { return ( <div className="center"> <HomePage/> </div> ); } } export default App; const appDiv = document.getElementById("app"); render(<App />, appDiv); Homepage.js import React, {Component} from 'react'; class Homepage extends Component { constructor(props) { super(props); } render() { return ( <div> test 1 </div> ); } } export default Homepage; -
Django how to install Requierements text even if it does not exist in a project that you downloaded from GitHub?
I have downloaded a Django Project from Github but The project does not include a requirement text. So I can not install the packages and I can not start it. Is there any way to solve this problem? -
How to add "variable.html" in include function of Django instead of hard coding the template name?
I want to render different HTML templates for each product detail view. I used this url pattern path('product-detail/<int:pk>', views.ProductDetailView.as_view(), name='product-detail'), Here is the view for product detail view class ProductDetailView(View): def get(self, request, pk): product = Product.objects.get(pk=pk) return render (request, 'esell/productdetail.html', {'product':product}) Here is the detail template <h2>{{ product.title }}</h2> <hr> <p>Product Description: {{ product.description }}</p> I want different detail templates to show for different product clicking on the product url. I tried to name the different html templates based one their id name like this "1.html" and tried to add include function to render different templates based on their id name like this {% include '{{product.id}}.html' %} But it's not working. Is there any way to add variable like that in include or other way to complete this task? -
Python, django: I would like to put objects within the 'input' tag or 'select' tag on form. ..in order to transfer the objects to the booking_form
User put some information in the price inquiry form and hit the calculate button User is moved to the page displaying the price with the information user put in the form If user is happy with the price and wanna go ahead booking, then there is a booking button Once user hit the booking button, user can access to the booking_form On the booking form, User can see the information he put before, so he does not have to put them in again. -- this is what I wanted So far, I did successfully upto no 4. I would like to transfer the information user put and the price calculated into the booking_form. but input tag does not allow {{ object }} inside tag. To make you understood better, I have attached the 'price_detail.html' below. {% extends 'basecamp/base.html' %} {% block content %} <form action="{% url 'booking_form' %}" method="post"> {% csrf_token %} <div class="container py-4 py-sm-7 text-center"> <div class="py-md-6"> <h1 class="text-light pb-1"> The price : $ {{ price }} </h1> <p class="fs-lg text-light" >{{ flight_date }} | {{ flight_number }} | {{ suburb }} | {{ no_of_passenger }} pax</p> <br/> <button class="btn btn-warning" type="submit">Book now</button> </div> </div> </section> {% endblock … -
How can I add a Bootstrap class to a 'Button' element through javascript?
I am trying to create a button with the Bootstrap class = "btn btn-info" through javascript, but instead of creating a styled Button, it just creates a plain HTML button. Code let diva = document.createElement('div'); diva.class = 'fluid-container'; let newContent = document.createElement('textarea'); newContent.id = 'content'; newContent.class = 'form-control'; newContent.rows = '2'; newContent.style = 'min-width : 100%'; newContent.placeholder = 'Add argument infavor'; //button = <button class="btn btn-info col-5" type="button" id="against"><b>Against</b></button> let btn = document.createElement('button'); btn.type = 'submit'; btn.class = 'btn btn-info'; btn.innerHTML = "Submit"; diva.appendChild(newContent); diva.appendChild(btn); parent = document.getElementById("addingArgumentArea"); parent.appendChild(diva); I am trying to use btn.class but it's not working. Why is this not working because the same method worked for the textfield created above and what is the solution? -
ModuleNotFoundError: No module named 'commentdjango'
I am trying to add comments to posts on my blog on this guide https://pypi.org/project/django-comments-dab/ but when doing migrations I get this error, thanks for any help -
Checking the input of the selected time in the time interval
I have a time interval from 09: 00 to 23: 00. I choose the time of 13: 00. How do I determine if this time is included in my interval? -
how to add data into 2 separate tables in django rest_framework
I have created a simple API and want to add data into 2 tables. For example I have created 2 tables in models.py class User(models.Model): userid = models.AutoField(primary_key=True) name = models.CharField(max_length= 100) age = models.IntegerField() gender = models.CharField(max_length=100) class Meta: db_table = 'user' class Detail(models.Model): address = models.CharField(max_length=100) phone = models.IntegerField() details = models.CharField(max_length=100) class Meta: db_table = 'detail' serializers.py class UserSerializer(serializers.ModelSerializer): name=serializers.CharField(required=True) age = serializers.IntegerField(required=True) gender = serializers.CharField(required=True) class Meta: model = User fields= '__all__' class DetailSerializer(serializers.ModelSerializer): address = serializers.CharField(required=True) phone = serializers.IntegerField(required=True) details= serializers.CharField(required=True) class Meta: model = Detail fields= '__all__' suppose I am passing the json data as { "name" : "abc", "age" : 20, "gender" : "Male", "address" : "xyz", "phone" : 454545454, "details" : "lorem epsum" } is it possible to insert data into both the tables?. name, age & gender should be inserted into User table & and address , phone & details into Detail table. I have tried many things hence I have nothing to show in views.py -
Create dynamic graphene arguements class
Just started using graphene for my backend, I have three types of users, they all have username, email and user_type as required, but the rest are optional. Instead of of creating 3 mutation classes, I'm trying to implement just one generic CreateUser Class My current implementation is: class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: # user = graphene.ID() email = graphene.String(required=True) password = graphene.String(required=True) user_type = graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() street_address = graphene.String() city = graphene.String() state = graphene.String() zip_code = graphene.Int() date = graphene.Date() ... #so on def mutate(self, info, email, password, user_type, **kwargs): user = CustomUser.objects.create( username=email, email=email, user_type=user_type, password=password, ) ... # code where I use kwargs return CreateUser(user=user) QUESTION: Is there a way to create the class Arguments: dynamically at runtime? -
Optimal coding in django
I have been asked which of the following methods is more optimal? I want to show the best-selling and latest products to users.In method A, I query the database twice. In method B, I only query product models once, and in the template, I use filters to display the best-selling and newest. Is the second method more logical and better than the first method? I have been asked which of the following methods is more optimal? I want to show the best-selling and latest products to users.In method A, I query the database twice. In method B, I only query product models once, and in the template, I use filters to display the best-selling and newest. Is the second method more logical and better than the first method? A : def home(request): create = Product.objects.all().order_by('-create')[:6] sell = Product.objects.all().order_by('-sell')[:6] return ... B: def home(request): products = Product.objects.all() return ... my template: for sell: {% for product in products|dictsortreversed:'sell'|slice:":8" %} -------------------- for create : {% for product in products|dictsortreversed:'create'|slice:":8" %} -
Django AJAX form and Select2
I am rendering a form on to my site with AJAX (view below) def add_property_and_valuation(request): """ A view to return an ajax response with add property & valuation form """ data = dict() form = PropertyForm() context = {"form": form} data["html_modal"] = render_to_string( "properties/stages/add_property_and_valuation_modal.html", context, request=request, ) return JsonResponse(data) The form and modal render on button click with the following JQuery code: $(".js-add-property").click(function () { var instance = $(this); $.ajax({ url: instance.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#base-large-modal").modal("show"); }, success: function (data) { $("#base-large-modal .modal-dialog").html(data.html_modal); } }); }); The issue I am having is that I am trying to use Select2 and because the form is being rendered after the DOM has loaded Select2 isn't working. Does anyone have a way to work around this? Watch for the DOM to change and enable Select2? Many thanks -
How to run an asynchronous curl request in Django rest framework
How to run an asynchronous curl request in Django rest framework. The request should be running background. my code is like: def track(self, appUserId, appEventName, appEventData): asyncio.run(self.main(appUserId, appEventName, appEventData)) async def main(self, appUserId, appEventName, appEventData): async with aiohttp.ClientSession() as session: tasks = [] task = asyncio.ensure_future(self.sendData(session, { "userId": self.appUserIdSandbox if (self.sandBoxEnabled == True) else appUserId, "eventName": appEventName, "eventData": appEventData })) tasks.append(task) task_count = await asyncio.gather(*tasks) async def sendData(self,session, appEventData): response = {} payload = json.dumps(appEventData) headers = { "Authorization": self.__authKey, "Cache-Control": "no-cache", "Content-Type": "application/json", } async with session.post(self.__apiUrl, headers=headers, data=payload) as response: result_data = await response.json() return response