Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get selected <div> from loop of multiple <divs> in Django template
I want to make a entry into the database using a button for which I have an event listener which is getting the data and making a ajax request. My code looks like this: home.html -> {% for fig in user_figs %} <div class='card'> {% if fig.chart %} <input type="hidden" id="card_chart" value="{{ fig }}"> <input type="hidden" id="card_filter_id" value="{{ fig.filter_id }}"> {{ fig.chart|safe }} {% endif %} </div> {% endfor %} model looks like this: class Card(models.Model): filter_id = models.CharField(max_length=120) title = models.CharField(max_length=120) chart = models.TextField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE) dashboard = models.ForeignKey(Plot, on_delete=models.SET_NULL, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if(len(self.filter_id) == 0): self.filter_id = str(uuid.uuid1()) super(Card, self).save(*args, **kwargs) def __str__(self): return f"Card title: {self.title} Card id: {self.filter_id}" The event listener in JS looks like this: save_changes_button.addEventListener('click', ()=>{ console.log("SAVE CHANGES BUTTON CLICKED") const card_id = document.getElementById('card_filter_id').value console.log(card_id) const form_data = new FormData() form_data.append('csrfmiddlewaretoken', csrf_token) form_data.append('name', name_of_dashbaord) form_data.append('title', title) form_data.append('chart', fig) form_data.append('card_id', card_id) $.ajax({ type: 'POST', url: '/card/save/', data: form_data, success: function(response){ console.log(response) }, error: function(error){ console.log(error) }, processData: false, contentType: false, }) }) now when user clicks the button, I want to make an entry into the database which looks like this: def create_card_view(request): if(request.is_ajax()): name … -
Python 3 and Django: write Georgian text to PDF file
The problem was to write Georgian text to PDF file. I have tried several encodings, however, this didn't solve the problem. Also I tryd to use some fonts, but it hasnot any goal. I need help.. i use xhtml2pdf modul def customer_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') customer = get_object_or_404(id, pk=pk) template_path = 'test.html' context = {'customer': customer} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename= "report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response, encoding='utf-8' ) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response -
Django- some images are missing sometimes can you help me
On the website I made with Django, I take 6 photos from the database from the same object, but while projecting them to html, some of them are missing from time to time. Can you help me? Below one is my codes Urls.py Here my url,settings,view and html code from django.urls import path, include, re_path from . import views from django.conf import settings from django.conf.urls.static import static from django.views.static import serve urlpatterns = [ path('', views.index, name='index'), path('signin',views.signin, name='signin'), path('register',views.register, name='register'), path('answers', views.answers, name='answers'), path('logout',views.logout,name='logout'), path('help',views.help,name='help'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,}),] Settings.py STATIC_URL = '/static/' STATIC_ROOT = '/home/static' STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = '/home/media' MEDIA_DIRS = (os.path.join(BASE_DIR,'media'),) views.py questionlist = [] answerlist = [] if(each.questionimg != ""): questionlist.append(each.questionimg) if(each.questionimg2 != ""): questionlist.append(each.questionimg2) if(each.questionimg3 != ""): questionlist.append(each.questionimg3) if(each.answer != ""): answerlist.append(each.answer) if(each.answer2 != ""): answerlist.append(each.answer2) if(each.answer3 != ""): answerlist.append(each.answer3) if(each.answer4 != ""): answerlist.append(each.answer4) if(each.answer5 != ""): answerlist.append(each.answer5) flag = False context = { "questionlist": questionlist, "answerlist": answerlist} return render(request,'answers.html',context) ``` Html {% for questionphoto in questionlist %} <img src="media/{{ questionphoto }}" class="img-fluid"> {% endfor %} -
Django - Replace model fields values before save
Just to note: I know about overwriting Model's .save() method but it won't suit me as I explained it at the end of my question. In one of my projects, I've got more than of 30 database Models and each one of these models accept multiple CharField to store store Persian characters; However there might be some case where users are using Arabic layouts for their keyboard where some chars are differ from Persian. For example: The name Ali in Arabic: علي and in Persian: علی Or even in numbers: 345 in Arabic: ٣٤٥ And in Persian: ۳۴۵ I need to selectively, choose a set of these fields and run a function on their value before saving them (On create or update) to map these characters so I won't end up with two different form of a single word in my database. One way to do this is overwriting the .save() method on the database Model. Is there any other way to do this so I don't have to change all my models? -
Django Admin change/modify the text "Add another" for inlines
In Django Admin, how can you change the text "Add another" for inlines? I am not referring to the object name ("Add another ObjectName"), that you can change with "verbose_name". I am referring to the words "Add another". For example to change "Add another Company" to "Include Company". I found that i can override directly the django/contrib/admin/helpers.py file. However it is not the best possible solution. What is the best/correct way to override helpers.py file? Where do i put the new helpers.py file? What other option are there to modify the text "Add another"? -
Django 'jsonify' is not a registered tag library. Must be one of:
I am working on a django project where Installed a package called jsonify which is to be used in the django template from https://pypi.org/project/jsonify/ & added in the installed apps: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "jsonify", "main", ] In my local environment it works just fine but when I deployed to heroku I keep 'jsonify' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static to_and tz Also note I have also made my own custom template tag "to_and" which works perfectly fine. This only happens in production in heroku and not in my local envirnoment. Thanks in advance -
How to put button value to database Django
do you have some tips how to put buttons values to the Django sqlite database? I have a page with some buttons with theirs values and some final button, which would send the buttons values to the database after the final button click. Thanks. -
Regex: how to extract incomplete date and convert
How can I get a date that may not contain the month or the day? Right now I only know how to break the date date_n= '2022-12' match_year = re.search(r'(?P<year_only>(?P<year>\d+))', date_n) match_month = re.search(r'(?P<whole_date>(?P<year>\d+)-(?P<month>\d+))', date_n) match_day = re.search(r'(?P<whole_date>(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+))', date_n) year = match_year.group('year_only') month = match_month.group('month') day = match_day.group('day') Try and Except does not work. -
How to add my TimedRotatingFileHandler to django logger?
I'am actually using my own logger (tools\logger.py) : ... logger = logging.getLogger("MyPersonalLogger") ... fh = handlers.TimedRotatingFileHandler( os.path.join(LOG_DATA_PATH, '{:%Y-%m-%d}.log'.format(datetime.now(tz=ZoneInfo("Europe/Paris")))), when='midnight', interval=1, backupCount=30, encoding='utf-8', delay=False, utc=False, atTime=None, errors=None) formatter = logging.Formatter('%(asctime)s | %(levelname)-8s | %(name)-8s | %(module)-8s | %(message)s', datefmt='%H:%M:%S') formatter.converter = lambda *args: datetime.now(tz=ZoneInfo("Europe/Paris")).timetuple() fh.setFormatter(formatter) logger.addHandler(fh) In django I'am trying to add my handler fh to the django logger without success... in settings.py import logging import tools.logger LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': {... }, 'handlers': {... }, 'loggers': { 'django': { 'handlers': ['console'], #defined in handlers up 'level': "DEBUG", 'propagate': True, } } } # ADDING my_logger = logging.getLogger('django') my_logger.addHandler(tools.logger.fh) And it doesn't work. Logging on console for django is working but clearly not for my TimedRotatingFileHandler fh. -
If-In statements not working as intended in Django Templates
I am trying to execute the following in python in a .html file in a Django environment: {% if data.author in s.suscriptions %} <p>Print this statement</p> {% endif %} data.author -> Johnny s.suscriptions -> JohnnySarahMatt In this code, data.author is just a string so upon testing data.author = Johnny. s.suscriptions is another string and will have an output something like JohnnySarahMatt. According to Django Documentation the in operator should work. But it is not, I can't locate what the issue actually is. I am a bit new to Django so I need some help on this. -
Django forms: Referecing variable defined in views def as placeholder within forms
I'm using Django and trying to reference a 'topic' available within a def in views as a placeholder that I had referenced from a url. In the code below, 'Replace this' should show the content of 'topic' as defined in 'def editpage(request, topic)' but I cannot seem to get the reference to work. from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django import forms from . import util class EditPageForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Replace this', 'class': 'form-control'})) def editpage(request, topic): return render(request, "encyclopedia/editpage.html", {"form": EditPageForm(), "topic":f"{topic}" }) My attempt was to swap 'Replace this' with f'{topic}', but it does not appear to work. from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django import forms from . import util class EditPageForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': f'{topic}', 'class': 'form-control'})) def editpage(request, topic): return render(request, "encyclopedia/editpage.html", {"form": EditPageForm(), "topic":f"{topic}" }) Instead, I get an error that 'topic' is not defined. Thanks in advance! -
Not able to access fields inside Div in Django forms
What works fine <form action = "{% url 'dashboard'%}" method = "POST"> {% csrf_token %} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name"> <input type="submit" value="OK"> </form> What does NOT work... <form action = "{% url 'dashboard'%}" method = "POST"> {% csrf_token %} <div class="col-lg-3 col-md-3 col-sm-12 p-0"> <input type="text" id="cve" class="form-control search-slt" placeholder="Enter CVE"> <input type="submit" value="OK"> </div> </form> Whenever I have values inside DIV tag, inside a form, The POST request does not contains values of DIV fields. -
'ManyToManyDescriptor' object has no attribute 'add' in Django with PostgreSQL
I am trying to store some data in my database, where 2 different model refer each other with 'Many-to-Many' fields. my models.py: class CorrectAns(models.Model): ansId = models.IntegerField(primary_key=True) responseText1 = models.TextField(null=True, blank=True) isDeleted = models.BooleanField(default=False) questionRef = models.ManyToManyField('Questions') class Questions(models.Model): questionId = models.IntegerField(primary_key=True) groupId = models.IntegerField(default=0) questionTitle = models.TextField() correctAnsRef = models.ManyToManyField(CorrectAns, related_name="questionReletedResponses") my views.py: for i in QuestionsList: questionObj = Questions( questionId = i['Id'], groupId = i['GroupId'], questionTitle = i['QuestionTitle'], ) questionObj.save() for j in i['Responses']: correctAnsObj = CorrectAns.objects.create( ansId = j['Id'], responseText1 = myResponseText1, isDeleted = j['IsDeleted'], ) correctAnsObj.questionRef.add(questionObj) correctAnsObj.save() Questions.correctAnsRef.add(correctAnsObj) return now it shows error with line: Questions.correctAnsRef.add(correctAnsObj) Like: 'ManyToManyDescriptor' object has no attribute 'add' Please suggest how can I fix this? -
Django Session Auth and DRF Knox JWT
I have an API from which users can login to get a token so they can make requests, etc and I have also made a a session login as there are a few scenarios where I need the user session token. Now if a user logs in to the API and afterwards they need to login using the session Auth its all good however the reverse does not work. If you are logged in using session Auth and then want to login via the API to release a token I get a response of Forbidden. Could someone please offer some insight? -
JWT Authorization multiple role in django rest framework using simple-jwt
I have a django website using django-rest-framework and simple-jwt for authentication. Docs: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/index.html My website have 2 role with different capability. I have to authorize them. But I can't find how to do it. Anyone can give me an example or docs to do this function. Thank you very much. -
How to implement a verification system? Django
The task is to implement a verification system for the following actions: registration, password reset, change of email address, change of phone number. What do I mean by this task? Need to generate tokens and then send them to user email address or phone number. After using them, user will be verified. For myself, I have identified a bunch of options, but I don’t know which one to choose. Generate the same type of token for SMS and email. This token is a code, six-digit, for example. Store them in redis, where the key is the user id and the value is the token itself. When the code comes from the client, search for it in redis. If it does not exist, then it is possible that it expired, or it did not exist at all. Store codes in the Django model, delete expired ones on access and make a management command so that we can delete those that have not been accessed. Generate only digital codes for SMS, and character tokens for email. It is possible that there is no best option at all among those listed. Please tell me the best practices. I am interested in what method … -
Problem with testing custom admin actions
Running into some problems when testing my custom admin actions. First I can show you an example of a test that works and the actions it's testing. custom action, Product model @admin.action(description="Merge selected products") def merge_products(self, request, queryset): list_of_products = queryset.order_by("created_at") list_of_products = list(list_of_products) canonical_product = list_of_products[0] list_of_products.remove(canonical_product) for p in list_of_products: for ep in p.external_products.all(): ep.internal_product = canonical_product ep.save() p.save() canonical_product.save() related test class MockRequest(object): pass class ProductAdminTest(TestCase): def setUp(self): self.product_admin = ProductAdmin(model=Product, admin_site=AdminSite()) User = get_user_model() admin_user = User.objects.create_superuser( username="superadmin", email="superadmin@email.com", password="testpass123" ) self.client.force_login(admin_user) def test_product_merge(self): self.boot1 = baker.make("products.Product", title="Filippa K boots", id=uuid4()) self.boot2 = baker.make("products.Product", title="Filippa K boots", id=uuid4()) self.external_product1 = baker.make( "external_products.ExternalProduct", internal_product=self.boot1 ) self.external_product2 = baker.make( "external_products.ExternalProduct", internal_product=self.boot2 ) self.assertEqual(self.boot1.external_products.count(), 1) self.assertEqual(self.boot2.external_products.count(), 1) request = MockRequest() queryset = Product.objects.filter(title="Filippa K boots") self.product_admin.merge_products(request, queryset) self.assertEqual(self.boot1.external_products.count(), 2) self.assertEqual(self.boot2.external_products.count(), 0) Might not be the pretties test but it works, so does the action. The code above works as it should but has been running into problems when trying to test an almost identical action but for another model. custom action, Brand model @admin.action(description="Merge selected brands") def merge_brands(self, request, queryset): qs_of_brands = queryset.order_by("created_at") list_of_brands = list(qs_of_brands) canonical_brand = list_of_brands[0] for brand in list_of_brands: if brand.canonical: canonical_brand = brand list_of_brands.remove(canonical_brand) … -
Trouble in setting only one serializer field to read_only Django Rest Framework
I have this model serializer and it has a lot of fields I want to use fields="__all__" but still be able to set one field to read_only = True. I tried having it like this: class InstitutionSerializer(serializers.ModelSerializer): class Meta: model = Institution fields = "__all__" def __init__(self, *args, **kwargs): super(InstitutionSerializer, self).__init__(*args, **kwargs) for field in self.fields: if field == "owner": self.fields[field].read_only = True But it still flags "owner": ["This field is required."] which is unneccessary for me because I want it to be able to set it on my view. I also tried extra_kwargs = {"owner": {"read_only": True}} and read_only_fields = ("owner",) but still fails. -
clean() method in Django ModelForm to avoid duplicate entries creates another instance upon updating the data. And doesn't even save a new instance
I have a few models, two of which are as follows: class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) pattern = RegexValidator(r'(RT|rt|rT|Rt)\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') rt_number=models.CharField(max_length=15, validators=[pattern]) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=0) approval_date=models.DateField(default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) class Discharge(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) date_of_discharge=models.DateField(default=None) mould_charges=models.DecimalField(max_digits=7, decimal_places=2, default=0, blank=True) ct_charges=models.DecimalField(max_digits=7, decimal_places=2, default=0, blank=True) discharge_updated=models.BooleanField(default=False) The views to save the new instance and update the existing one respectively, are: 1. def discharge_view(request): if request.method=='POST': fm_discharge=DischargeForm(request.POST, request=request) if fm_discharge.is_valid(): discharge=fm_discharge.save() ipd=IpdReport.objects.create(patient=discharge.patient, package=Package.objects.filter(patient=discharge.patient).order_by('-id').first(), receivables=Receivables.objects.filter(patient=discharge.patient).order_by('-id').first(), discharge=discharge) if discharge is not None: OngoingReport.objects.filter(ipdreport__patient=discharge.patient).delete() package=Package.objects.filter(patient=discharge.patient).order_by('-id').first().patient_type.patient_type if discharge.discharge_updated==False and package!='CASH': UnclaimedPendingCases.objects.create(ipdreport=ipd) elif discharge.discharge_updated==True and package!='CASH': ClaimedPendingCases.objects.create(ipdreport=ipd) fm_discharge=DischargeForm(request=request) return render(request, 'account/discharge.html', {'form':fm_discharge}) else: fm_discharge=DischargeForm(request=request) return render(request, 'account/discharge.html', {'form':fm_discharge}) def update_discharge_view(request, id): di1=Discharge.objects.get(pk=id) fm1=di1.discharge_updated if request.method=='POST': print(request.POST) di=Discharge.objects.get(pk=id) form=DischargeForm(request.POST, instance=di, request=request) if form.is_valid(): discharge=form.save() else: di=Discharge.objects.get(pk=id) form=DischargeForm(instance=di, request=request) return render(request, 'account/update_discharge.html', {'form':form}) The ModelForm looks as below: class DischargeForm(ModelForm): class Meta: model=Discharge fields='__all__' widgets={ 'date_of_discharge': DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): self.request=kwargs.pop('request') self.instance=kwargs.pop('instance') super(DischargeForm, self).__init__(*args, **kwargs) def clean(self): super().clean() pt=self.request.POST.get('patient') if not self.instance: rec=Receivables.objects.filter(patient__pk=pt).order_by('-id').first() if Discharge.objects.filter(patient__pk=pt, date_of_discharge__gt=rec.approval_date).exists(): raise ValidationError('The patient has already been discharged!') I want the discharge to be saved only once, for each time the patient gets treatment. Though it can be updated. Earlier I had written … -
Django form is not being valid, how to fix it?
I am new to Django and I was creating an e-commerce store using Django. I successfully created User Login Form which works perfectly, but I am stuck at User Registration Form. It is not being valid. My forms.py: from django import forms from django.forms.widgets import PasswordInput class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class UserRegistrationForm(forms.Form): username = forms.CharField() email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() data = self.cleaned_data password = cleaned_data.get('password') password2 = cleaned_data.get('password2') if password2 != password: raise forms.ValidationError("Passwords must match") return data My register.html <div> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" name="Register"> </form> </div> My login.html <div> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" name="Login"> </form> </div> My views.py from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from .forms import UserLoginForm, UserRegistrationForm # Create your views here. def userRegistrationPage(request): form = UserRegistrationForm() context = { 'form': form } if request.method == 'POST': form = UserRegistrationForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") print(username, password) else: print("Form is not valid") return render(request, 'index/register.html', context) def userLoginPage(request): form = UserLoginForm() context = { 'form': form } … -
How do I JSON parse a Django queryset?
So I'm trying to parse each object in my Django queryset, and deal with the data through JavaScript. Below is my code (simplified) : views.py (using Django Paginator, but the basic idea is the same.) def main_page(request): all_contents = Contents.objects.all() paginator_contents = Paginator(contents,10) page = request.GET.get('page') all_contents_paginated = paginator_contents.get_page(page) context = { 'contents' : contents, 'all_contents_paginated' : all_contents_paginated } return render(request, 'main/home.html', context) template {% for c in all_contents_paginated %} <div class="text-m"> {{c.author}} </div> <div class="text-s" onclick="DetailModal('{{c}}')"> {{c.body}} </div> {% endfor %} <script> function DetailModal(c) { } </script> Now obviously, the '{{c}}' cannot be parsed into JSON since it's string. I want to parse it into JSON in function DetailModal() and display the data in a separate modal element or do any other stuff with each data. But I can't figure out how to parse each object in the Django queryset. Any ideas? Thanks. -
Fill out Django form with data obtained from URL
I want to create a new Fallacy (see models.py) via the form to which I get over the url path('<slug:slug_tree>/new/', views.CreateFallacyView.as_view(), name='create_fallacy'),. So the user is on the TreeDetailView (which corresponds to a certain Tree), and he can add a new Fallacy to this tree. The user should input title and detail, but the Tree (ForeignKey) should be assigned in the code. It should be assigned to the corresponding Tree from which he was directed to the CreateFallacyView. The slug of the tree is inside the URL, so I thought I could use that information somehow, but I have no idea how I can proceed with that information. Any help is appreciated! Or probably there are other more elegant solutions? Many thanks! models.py class Tree(models.Model): title = models.CharField(max_length=50) detail = models.TextField() slug = models.SlugField(allow_unicode=True, unique=True, null=True, blank=True) class Fallacy(models.Model): title = models.CharField(max_length=50) detail = models.TextField() tree = models.ForeignKey(Tree, related_name='fallacy', on_delete=models.CASCADE) views.py class CreateFallacyView(generic.CreateView): form_class = forms.FallacyForm forms.py class FallacyForm(forms.ModelForm): class Meta: model = models.Fallacy fields = ('title', 'detail') urls.py app_name = 'argtree' urlpatterns = [ path('', views.TreeListView.as_view(), name='all'), path('<slug:slug_tree>/', views.TreeDetailView.as_view(), name='tree_detail'), path('<slug:slug_tree>/new/', views.CreateFallacyView.as_view(), name='create_fallacy'), -
I’ve set the exact date in admin but it keeps saying that there’s no available rooms. Maybe incorrect date format? Thanks in advance
In models.py This is the models.py I used DateTimeField for this In views.py this is the views to check if the room is available or not -
django get_queryset() with conditional filter()
I have a custom model manager on model such as: class MyCustomManager(models.Manager): def doFoo(self, user, s_format): qs = super().get_queryset().filter(created_by=user) return qs which is returning data based on the user passed as the argument. However, how would I go about adding more AND conditions to the above query based on if conditions? Something like this: class MyCustomManager(models.Manager): def doFoo(self, user, s_format): qs = super().get_queryset().filter(created_by=user) if <condition 1>: qs.filter(mode='A') elif <condition 2>: qs.filter(mode='B') return qs If I do the above, even if <condition 2> is true, it's not generating created_by=1 AND mode='B' SQL I'm basically trying to do the equivalent of the following but split by conditions qs = super().get_queryset().filter(created_by=user, mode='A') -
How to configure celery for concurrent execution with multi process?
I have a task that talks to an external API, the json response is quite large and I have to make this call multiple times followed by further python processing. To make this less time-consuming, I initially tried: def make_call(*args, **kwargs): pass def make_another(*args, **kwargs): pass def get_calls(): return make_call, make_another def task(*args, **kwargs): procs = [Process(target=get_calls()[i], args=(,), kwargs={}) for i in range(3)] _start = [proc.start() for proc in procs] _join = [proc.join() for proc in procs] # transaction.on_commit(lambda: task.delay()) However, I ran into an ```AssertionError: daemonic processes are not allowed to have children. What would be my best approach to speed up a celery task with additional processes?