Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Write a view model in Django
How to write a view model in Django which is similar to database view? PS: A view can combine data from two or more table. In my case, i want to combine 5 table in this view. -
Django Template loader searching template in another app
The template loader is searching template file in another app instead of current app. Tn this case, template loader should search in home/templates directory instead its searching template in polls/template directory . Please help my code template loader post-mortem -
Which is the best protocol for video streaming ,websockets or https? [duplicate]
I had created a music website (Django+React) with https protocol and when users play music in frontend they were not able to seek or jumb to middle track of playing music. If I use websockets, can I overcome this ? I have seen many videos in internet which are capable to seek/backward/speed the tracks, do they use websockets ? -
Django Model Form: Foreign Keys: Override Dropdown Menu and Allow For New Entries
I am developing a dictionary application using Django. I am having trouble successfully creating a form using Django's ModelForm class that allows users to submit new definitions to BOTH existing AND new dictionary headwords. Here is my models.py: class Headword(models.Model): headword = models.CharField(max_length=64, unique=True) class Definition(models.Model): definition = models.CharField(max_length=64) headword = models.ForeignKey(Headword, related_name="definitions_headword") Here is my forms.py: class DefinitionForm(forms.ModelForm): class Meta: model = Definition fields = ["headword", "definition"] Here is my HTML form: <form action="{% url 'dictionary:define' %}" method="post"> {% csrf_token %} {{ form }} <button type="submit">Define</button> </form> The result of all this is a form with 1) a dropdown menu containing all the headwords already in the database, 2) a text input field for the definition, and 3) a submission button. With the above code, therefore, the user is ONLY allowed to add definitions to headwords that already exist. As I said, I would like to change that and have this form such that users are able to submit definitions to BOTH existing headwords (the ones in the dropdown menu), AND new ones (ones that the user can just type in). This means I wouldn't want a dropdown menu at all in the form, but just two unconstrained text … -
SystemError: Parent module 'setuptools' not loaded, cannot perform relative import
I'm currently using google cloud platform ubuntu vminstance to run vscode. Whenver I run python3 __init__.py, it will return this error: Traceback (most recent call last): File "__init__.py", line 4, in <module> from BatteryModel.batterymodel.conn.sqlDatabase import sqlDatabase File "/home/phuongdoanmr/sensa/SENSA_2020v1/BatteryModel/batterymodel/conn/sqlDatabase.py", line 3, in <module> import django.db as db File "/home/phuongdoanmr/.local/lib/python3.5/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/phuongdoanmr/.local/lib/python3.5/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 666, in _load_unlocked File "<frozen importlib._bootstrap>", line 577, in module_from_spec File "/home/phuongdoanmr/.local/lib/python3.5/site-packages/_distutils_hack/__init__.py", line 82, in create_module return importlib.import_module('._distutils', 'setuptools') File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 981, in _gcd_import File "<frozen importlib._bootstrap>", line 931, in _sanity_check SystemError: Parent module 'setuptools' not loaded, cannot perform relative import Could anyone please suggest a way to solve this problem. Thanks a lot. -
(Django) How to assign unique values to each user for something linked by ForeignKey?
My group project for school has us building a school management system. I have the following models: Student: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) User.is_student = True enrolled_courses = models.ManyToManyField(Session, blank=True) def __str__(self): return f'{self.user.last_name}, {self.user.first_name}' Session: class Session(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_date_start = models.DateTimeField() course_date_end = models.DateTimeField() def session_id(self): new_session_date = self.course_date_start.strftime('%Y') return f'{new_session_date}{self.course.number}{self.pk}' def __str__(self): return f'{self.course.number} - {self.course.title} - {self.session_id()}' Assignment: class Assignment(models.Model): session_link = models.ForeignKey(Session, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) due_date = models.DateField() title = models.CharField(max_length=50) total_points = models.IntegerField() points_earned = models.IntegerField(blank=True, null=True) objective = models.TextField() def __str__(self): return self.title The problem right now is if I save one value of points_earned to a user, it saves that value to all, since they're linked by the FK. What's the best way to handle it so each Student can have their own score for each assignment? -
Django bicrypt password different from ruby
I have ruby app with mysql database which has password stored.I don't know ruby but from internet what i found is that ruby stores password in bicrypt format. I created one user with password : Password123. What i printed in console was its encrypted password. Tasks: Now i am creating a django app which needs to be connected to same database.I need to verify password from same database.That is i used bicrypt algorithm in django dummy app and created user with same password : Password123. But encrypted text from ruby app and django app are different.It needs to be same for verification from django app. How to do this? Why bicrypt output of both language different. -
Failure to run Django app with Docker compose on the browser
I am working on a Django project, & I am using Docker Compose to set up and run a simple Django/PostgreSQL app. The problem is when I try to run the command "docker-compose up" the terminal gives me the URL to run on the browser but nothing happening in the browser. Can you help me if you have any idea, I will be so thankful. Dockerfile: FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ Docker-compose.yml: version: '3' services: web: build: . command: python src/products_projects/manage.py runserver 192.168.99.100:8000 volumes: - .:/code ports: - "8000:8000" redis: image: "redis:alpine" The Docker Terminal: ## . ## ## ## == ## ## ## ## ## === /"""""""""""""""""\___/ === ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ / ===- ~~~ \______ o __/ \ \ __/ \____\_______/ docker is configured to use the default machine with IP 192.168.99.100 For help getting started, check out the docs at https://docs.docker.com $ docker-machine ip 192.168.99.100 The results in the terminal: web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | August 31, … -
filter queryset based on django countries field
this is my viewset: class PollViewSet(viewsets.ReadOnlyModelViewSet): queryset = Poll.objects.all() serializer_class = PollSerializer() def get_queryset(self): country = self.kwargs.get('pk', None) if country is not None: django_countries.Countries.name(country) return self.queryset.filter(personality__country__name=country) else: country = self.request.user.preferred_country return self.queryset.filter(personality__country=country) model.py : class Poll(RulesModel): personality = models.OneToOneField(Personality, related_name='polls', on_delete=models.CASCADE) start_date = models.DateTimeField(null=True) end_date = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return 'poll#' + str(self.id) + ' ' + self.personality.name here it raises exception that "Unsupported lookup 'name' for CountryField or join on the field not permitted." this is raised in the if condition (else condition works perfectly fine). is there any other way of filtering the query set based on the country's name i actually want to view only the polls related to country passed as a param in the get url -
why am I not able to execute SQL query on my existing postgres database table?
for learning purpose I have migrated my database from SQLite to postgres recently with in my Django project, and it was successful. I am able to connect to the DB through below command sudo -u <username> psql -d <DB_name>; I am able to list the tables including the schema: \d But when I tried to query simple select query it give below error: select * from public.AUTHENTICATION_userprofile; ERROR: relation "public.authentication_userprofile" does not exist LINE 1: select * from public.AUTHENTICATION_userprofile; Table details: Schema | Name | Type | Owner --------+-----------------------------------+----------+---------- public | AUTHENTICATION_userprofile | table | postgres public | AUTHENTICATION_userprofile_id_seq | sequence | postgres Any suggestions please. Thank you -
TypeError: context must be a dict rather than JsonResponse
I am trying to use ajax in class based Listview for pagination but it's not working.I saw many tutorial of ajax pagination but all of them is with function based views. #views.py class HomePage(ListView): model = Video template_name = 'index.html' def get_context_data(self, **kwargs): context = super(HomePage, self).get_context_data(**kwargs) videos = Video.objects.filter(category='sub') paginator = Paginator(videos, 5) page = self.request.GET.get('page2') try: videos = paginator.page(page) except PageNotAnInteger: videos = paginator.page(1) except EmptyPage: videos = paginator.page(paginator.num_pages) context['videos'] = videos if self.request.is_ajax(): html = render_to_string('video/index2.html', context, request=self.request) return JsonResponse({'form' : html }) else: return context The error I getting using this views is:- TypeError: context must be a dict rather than JsonResponse. If you have any different ways to achieve this ajax pagination .Please mention that.Thank you in advance. -
django_filter on filtered Model
When i try to filter a model that i have queryed like this: products_model = Product.objects.filter(sub_category__name__iexact=sub) supplier_filter = SupplierFilter(request.GET, queryset=products_model ) products_model = supplier_filter.qs I get this error 'list' object has no attribute 'model' Does anyone know a way around it? Or am i just doing it wrong. I had an idea where i would get all objects then create a for loop and use the objects.get(id=pk) method for every product. But didnt get that to work. Thanks for help in advance! -
How can I get Django-Html dynamic loop on 2 table?
I have 2 tables Models.py class Spiders(models.Model): bot = models.ForeignKey(Bots,on_delete=models.CASCADE) spider_class = models.CharField(max_length=50,verbose_name="Örümcek Sınıfı") spider_name = models.CharField(max_length=200,verbose_name="Örümcek Adı",null=True) spider_url = models.CharField(max_length=200,verbose_name="Örümcek Adresi",null=True) spider_frequency = models.CharField(max_length=200,verbose_name="Spider Sıklığı", null=True) class Urls(models.Model): spider = models.ForeignKey(Spiders,on_delete=models.CASCADE) url_tag = models.CharField(max_length=200,verbose_name="URL Uzantısı") View.py def listMarkets(request): spiders = Spiders.objects.all() urls = Urls.objects.all() context={ 'spiders': spiders, 'urls': urls, } return render(request, 'index.html', context) index.html {% for spide in spiders%} <div class="card"> <div class="card-header row" id="heading{{spide.id}}"> <div class="col-2" style="padding-top:13px"> <h5 class="mb-0"><a href="#!" data-toggle="collapse" data-target="#collapse{{spide.id}}" aria-expanded="false" aria-controls="collapse{{spide.id}}">{{spide.spider_name}}</a></h5> </div> <div class="col-6"> <table class="table"> <tbody> <tr> <td>{{spide.spider_url}}</td> <td>{{spide.spider_frequency}}</td> {% endfor %} </tr> </tbody> </table> </div> <div class="col"> <tr> <td><button type="button" class="btn btn-info" style="margin-bottom: unset;" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Linkleri gir</button></td> <td><a href="#" class="btn btn-info" style="margin-bottom: unset;">Güncelle</a></td> <td><a href="#" class="btn btn-info" style="margin-bottom: unset;">Getir</a> </td> <!--<td><a href="#" class = "btn btn-danger" style="margin-bottom: unset;">Sil</a> </td>--> </tr> </div> </div> <div id="collapse{{spide.id}}" class=" card-body collapse" aria-labelledby="heading{{spide.id}}" data-parent="#accordionExample"> <table class="table table-striped"> <thead> </thead> <tbody> <tr> {% for spider in spiders %} <td>{{spider.id.url_tag (or something like this)}}</td> //I want to write url_tag depend on spider_id (foreign key) <td>{{spider.id}}</td> <td>{{spider.spider_name}}</td> <td>{{spider.spider_url}}</td> <td>{{spider.spider_frequency}}</td> {% endfor %} </tr> </tbody> </table> </div> </div> {% endfor %} I want to write url_tag depend on spider_id because every spider has more than 1 url_tag and I want … -
why webpage shows empty after running python manage.py runserver
why webpage shows empty after running python manage.py runserver python manage.py runserver shows black page. why html templates are not loading. block content is not fetching data from templates in base.html if i put all login.html in base.html it load template but after use of block and extends it shows empty. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('account.urls')), ] urls.py (account) from django.urls import path, include from account import views urlpatterns = [ path('', views.account, name='account'), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def account(request): return render(request, 'account/base.html') base.html <!doctype html> {% load static %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <title>Account</title> </head> <body> {% block content %} {% endblock content %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> </body> </html> login.html {% extends 'account/base.html' %} {% block content %} <!-- Login Form --> <div class="row justify-content-center" style="margin-top:250px;"> <form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" … -
Python Django, Pandas: ForeignKey, his attributes and calculation
Good day, is there any solution to access the attributes of a ForeignKey inside my models.py and also to calculate inside a dataframe? class Object(models.Model): name = models.Charfield(max_length=100, null=False, blank=False) price = models.Integerfield(default=0) class Amounts(models.Model): object = models.ForeignKey(Object, on_delete=models.CASCADE) amount = models.Integerfield(default=0) Let's say the existing objects are looking something like this: id | name | price 1 | name_a | 2 2 | name_b | 4 3 | name_c | 8 Now I got a dataframe that looks something like this: id | object | amount 1 | name_a | 12 2 | name_b | 7 3 | name_c | 19 Is it possible to get the other attributes of the (via foreignkey) connected data and also to calculate inside the dataframe(in this case: price x amount)? Possible result: id | object | amount | price | calc 1 | name_a | 12 | 2 | 24 2 | name_b | 7 | 4 | 28 3 | name_c | 19 | 8 | 152 Thanks for all your help! -
couldn't import django:importError
I am working on a Django project and at the beginning everything was going well . But for say 2 days i'm not more able to run my project using the Python run manage.py it gives me this error Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment ? I use Anaconda as virtual environment . During my debugging process I checked the installed packages in the environment , and this is the output. I also use python 3.8 as interpreter but outside the virtual environment. -
How to split a string in django QuerySet object
In the view.py I am trying split an attribute value which is a long string. In a normal query: someposts = Posts.object.all()[3:5] should return: <QuerySet [object<first post>, object<second post>]> So then I query posts as follows as I need to split an attribute value (after this change I get the error): someposts = Posts.object.all().values('id', 'title', 'tags')[3:5] so it returns something like: <QuerySet [{'id': 2, 'title': 'first post', 'tags': ' X1, X2, X3,.., X10'}, {'id': 4, 'title': 'second post', 'tags': ' S1, S2, S3,.., S8'}] But I expect to receive tags as a list of stings, so what I did: splited_tags = [v['tags'].split(',') for v in someposts] for n, i in enumerate(someposts): someposts[n]['tags'] = splited_tags[n] and as the result <QuerySet [{'id': 2, 'title': 'first post', 'tags': [' X1', 'X2', 'X3',.., X10']}, {'id': 4, 'title': 'second post', 'tags': [' S1', 'S2', 'S3,.., 'S8']}] since I am passing someposts to my template: context = { 'someposts':someposts, } return render(request, 'app/home.html', context) and in home.html: {%for post in someposts %} <a class="avator" href="{% url 'user-post' post.author.username %}"></a> { % endfor %} I recieve this error: Reverse for 'user-post' with arguments '('',)' not found I think the problem is post.author.username since post is a string, … -
Django elasticsearch data synchronization
I want to use elasticsearch to index a model in django, this model is an map of database view. I want to know if django elasticsearch synchronized data after the storage of data in the other tables, or before that ?? -
Django timesince function is wrong
I want to create a function that returns the list of last points per vehicle that have sent navigation data in the last 48 hours. I create a view it works and it displays name correctly but I want to show that How long has it been since the data was sent. I use timesince but it shows wrong. It adds 13 hours and prints same hours for all data. I think it is related to my models because I cannot do anything about hours, minutes. like this How can I fix it? navigation.html <td>{{ result.datetime|timesince }}</td> models.py class Vehicle(models.Model): id = models.IntegerField(primary_key=True) plate = models.CharField(max_length=30) def __str__(self): return str(self.plate) class NavigationRecord(models.Model): id = models.IntegerField(primary_key=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) datetime = models.DateField(default=timezone.now) latitude = models.FloatField() longitude = models.FloatField() def __str__(self): return str(self.vehicle) views.py def get_48_hours(request): time_48 = datetime.now() - timedelta(hours=48) results = NavigationRecord.objects.filter(datetime__gte=time_48).order_by('-datetime') context = { 'results': results, } return render(request, 'navigation.html', context) Note: Any advice is accepted for improving my code. -
Django: Pagination wont centre on page 1
I have added in a template pagination I found and it works fine but wont centre on page 1 even with "text-centre" and "justify-content-center" as recommended by other answers. It looks fine on page 2 and 3... as can be seen below {% block pagination %} {% if is_paginated %} <div class="text-center"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> </div> {% endif %} {% endblock %} This is the code i used and this is what it looks like on page 1 and its pulling to the right. I currently don't have any CSS code for the pagination, though I have tried different options with no luck. If I remove the "text-centre" then page 1 is centred but pages 2/3 pull to the left, so I am a bit stumped. p.s this is my first django post so … -
How do I create a portable admin panel in Django
I need help I want to create a cms like wordpress using django I want to create a cms once and us it for all of my projects anyone can help me ? -
Read big PDF files django
I have a pdf file (500 MB) and it contains images . Now I have to tell when each image start and when it ends , like image 1 : start page 1 , end Page 2 . for that what I can do to read that much big files ? and which python lib can do this work of checking pages ? -
django.db.utils.OperationalError: no such table: polls_post
I'm looking at this problem for an hour but i cannot find what's wrong with this, when I run "python manage.py shell" and import like "from polls.models import Post " and call on the shell "Post.objects.all()" it shows an error like this "django.db.utils.OperationalError: no such table: polls_post" how can I solve this ? This is the polls.models.py ''' from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) ''' This is the 0001_initial.py ''' Generated by Django 3.1 on 2020-08-31 02:53 ''' from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('content', models.TextField()), ('date_posted', models.DateTimeField(default=django.utils.timezone.now)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] ''' -
Django __str__ return foreignkey title
Good day, I am currently experiencing an issue with my code. My goal is to have the most MostRevenueGeneratedForCurrentMonth attach to the Sales model with a Foreign Key and return the Foreign Key's Product Title but for some reason it keeps giving me an error saying 'Product' object has no attribute 'product_title' The sales Model class Sales(models.Model): """ This is the data Model for the sales data. This is where we will be saving products that have been sold so we can collect data for stats """ order_item_id = models.CharField(max_length=155) order_id = models.CharField(max_length=155) order_date = models.DateTimeField() sale_status = models.CharField(max_length=155) offer_id = models.CharField(max_length=155) tsin = models.CharField(max_length=155) sku = models.CharField(max_length=155) product_title = models.CharField(max_length=155) takealot_url_mobi = models.CharField(max_length=155) selling_price = models.CharField(max_length=155) quantity = models.IntegerField() warehouse = models.ForeignKey( Warehouse, on_delete=models.CASCADE, null=True) customer = models.CharField(max_length=155) takealot_url = models.CharField(max_length=155) shipment_id = models.CharField(max_length=155, null=True) po_number = models.CharField(max_length=155, null=True) shipment_state_id = models.CharField(max_length=155, null=True) shipment_name = models.CharField(max_length=155, null=True) promotion = models.CharField(max_length=155, null=True) def __str__(self): return self.product_title The MostRevenueGeneratedForCurrentMonth Model class MostRevenueGeneratedForCurrentMonth(models.Model): """ This is the data model for the most revenue generated products so we can easily keep track of it and sort through it to send to the API app to get serialized and sent to the frontend. """ … -
How to use multiprocess in django command?
I'm tring to use ProcessPoolExecutor in django command to get some results at same time. And I tried with below codes to get it # main codes import json import time import datetime from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor from redis import Redis from django.conf import settings from django.core.management.base import BaseCommand from thrift.transport import TSocket, TTransport from thrift.protocol import TBinaryProtocol from utils.cache import pool from services.analysis.thrift.Analysis import Client, Dashparam from api.analysis.models import MDashBoard redis_con = Redis(connection_pool=pool) class AnalysisThriftService(object): def __init__(self): ... def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.transport.close() class Command(BaseCommand): help = 'python manage.py --settings "xxx"' def add_arguments(self, parser): parser.add_argument('--dashboard_id', type=int, help="ID") @staticmethod def _handle_with_thrift(dashboard_id): try: print(dashboard_id) with AnalysisThriftService() as thrift_server: dashboard_result = ... except: import traceback traceback.print_exc() def handle(self, *args, **options): dashboard_id = options["dashboard_id"] if dashboard_id is None: dashboard_tables = [dashboard.id for dashboard in MDashBoard.objects.all()] with ProcessPoolExecutor(max_workers=5) as executor: executor.map(Command._handle_with_thrift, dashboard_tables) else: ... But I always get error like Process Process-5: Process Process-2: Traceback (most recent call last): File "D:\python3\lib\multiprocessing\process.py", line 258, in _bootstrap self.run() File "D:\python3\lib\multiprocessing\process.py", line 93, in run self._target(*self._args, **self._kwargs) File "D:\python3\lib\concurrent\futures\process.py", line 169, in _process_worker call_item = call_queue.get(block=True) File "D:\python3\lib\multiprocessing\queues.py", line 113, in get return _ForkingPickler.loads(res) File "C:\Users\Domob\Desktop\dev\myapi\analysis\management\commands\dashboard_schedule_task.py", line 15, in <modu le> …