Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i have problem activating my env using django with python in vscode
env\Scripts\activate when i want to activate my env they saying i cant cause the execution of the script its disabled and its hapens to me with every file in my django folder (except the html files) i would be glad if someone help me resolving this problem thanks you i want to create a html page using dgango and python (in vs code ) , to do that i need first to solve 2 problems 1- i need to solve the problem of django: they saying me that django is not found even thou i donwload it in my terminal of vs code ç 2- i have problem activating my envirement as u can see in the foto -
Celery raises `ValueError: not enough values to unpack (expected 3, got 0)` when calling task
I'm using Celery in a Django project to schedule notification tasks. When I start the Celery worker and the task runs, I get the following error: ValueError: not enough values to unpack (expected 3, got 0) Full traceback: File "celery\app\trace.py", line 640, in fast_trace_task tasks, accept, hostname = _loc ValueError: not enough values to unpack (expected 3, got 0) This happens when the following task is triggered: # core/tasks.py from celery import shared_task from django.utils import timezone from core.models import Notification @shared_task def send_scheduled_notifications(): now = timezone.now() notifications = Notification.objects.filter( is_read=False, send_at__lte=now ) for notification in notifications: print(f"Sending notification: {notification.title}") notification.is_read = True notification.save() Celery starts successfully and logs the task as received, but then immediately crashes with the error above. My environment: Windows 11 Python 3.13 Celery 5.5.1 Redis running locally I’ve confirmed the task runs fine when executed manually outside Celery. "I came across this similar question, but my error occurs in a different version of Celery and the task seems structured correctly." -
Django paginator page turns to list
I'm trying built a matrimonial site in Django. The following is the code for displaying a single profile at a time. unfiltered_list = profile_matches for profile in unfiltered_list: print("\n profile:",profile,"\n") profiles_list = profile_matches paginator = Paginator(profiles_list,1) page_number = request.GET.get('page', 1) profiles = paginator.page(page_number) profile_id = profiles.object_list.values('user_model_for_profile_id') The code works fine if I remove the for loop, but when I try to loop through the unfiltered list, 'profiles' becomes a list even though I haven't touched it, other than creating a variable that references to it. I get an Attribute error saying AttributeError: 'list' object has no attribute 'values' Is this a problem with Django itself? Or am I missing something? -
How to make authentication in django using rest framework?
I am currently working on a project called “Asset Management System.” I have created five models: AssetCategory, Asset, AssetDetails, AssetOut, and Person. Each of these models contains the following fields: AssetCategory: Name of the category of the asset Asset: Name of the asset AssetDetails: Description of the asset AssetOut: Amount of the asset that has been out of stock Person: Information about the person who owns the asset I have already developed an API for CRUD operations for these models. I am now trying to create an authentication API for my project. I would like to know how I can do this using Rest Framework(using JWT Authentication instead of tokens). Please note that you can update the above model as per your requirements. i have not tried im new to making authentication api. -
Uncaught SyntaxError: Unexpected end of input in Django Template (inline JS)
I'm developing a Django web application to visualize data from uploaded XML files. I'm encountering a persistent Uncaught SyntaxError: Unexpected end of input in the browser console when loading the data visualization page. This error prevents the JavaScript from running and the chart (using Chart.js) from displaying. Problem: When I navigate to the /visualizer/data-visualizer/ page, the browser console shows Uncaught SyntaxError: Unexpected end of input, pointing to a line number within the main HTML response (e.g., data-visualizer/:3149:80). The chart area on the page remains blank. Context: Django Version: 5.2 Python Version: [Your Python version, e.g., 3.9, 3.10] Operating System: Windows Web Server: Django Development Server (manage.py runserver) The application workflow is: Upload XML file -> Select data fields -> View visualization page (/visualizer/data-visualizer/). The visualization page is rendered by the VisualizerInterfaceView using the visualizer_interface.html template. The template includes Chart.js via a CDN and has an inline <script> block containing custom JavaScript logic to retrieve data from JSON embedded in the template and render the chart. Observed Behavior and Debugging Steps Taken: The Uncaught SyntaxError: Unexpected end of input error appears consistently in the browser console (tested in Chrome and Edge). Looking at the browser's "View Page Source" for the /visualizer/data-visualizer/ … -
How should a CLIENT_SECRET for OAuth be accessed?
I have a nextJs SPA and a Django web application. For authentication I am trying to implement OAuth with Google. From the articles I've read related to this I've understood that client_secret shouldn't be stored on the client_side in my case the nextJs app. What confuses me is that when a user tries to login they would need to access the client_secret. lets say I retrieve the client_secret through an API when the user tried to login and then use the retrieved client_secret. Wouldn't it still be exposed to potential malicious parties? What would be a secure way to store and retrieve the stored client_secret? I tried to follow the next-auth tutorial to setup Google OAuth but the client_id and client_secret and both stored on the nextJs application which go against recommendations related to OAuth implementations. -
Django, LoginRequiredMiddleware, login, and media
in a Django 5.2 application I discovered LoginRequiredMiddleware. It's a great system. However, I have some problems with the media. When a url has the @login_not_required() decorator, it's impossible to display uploaded images. in the console, when the page is loaded, django considers this as a next_url. [19/Apr/2025 08:11:34] "GET /media/identity/background.jpg HTTP/1.1" 302 0 [19/Apr/2025 08:11:34] "GET /?next=/media/identity/background.jpg HTTP/1.1" 200 3062 If the user is logged in, it works fine by declaring the images downloaded with MEDIA_URL like the examples below. If the user is anonymous, then the image is in error. <style> body{ background-image: url("{{ MEDIA_URL }}{{ identity.background }}") !important; } </style> <img src="{{ MEDIA_URL }}{{ identity.logo }}" style="width: auto; height: 100px;"> #settings.py # Media files MEDIA_ROOT = BASE_DIR / "media" MEDIA_URL = "/media/" Do you have any idea how to display the media? I've started to make a custom middelware but that's not the point. -
Can find an input value throught its id in a django generated table
I'm very new to javascript and must use it for a project in which i'm using a table and want to extract the value of an input field with id generated trough a Django function. i don't know if that could be relevent but i'm using datatable in this project. The HTML code looks like this: <head> <script src="{% static 'myProject/jQuery/jquery-3.7.1.js' %}"></script> <script src="{% static 'myProject/javaScript/datatables.min.js' %}"></script> <script src="{% static 'myProject/javaScript/checkFunc.js' %}" defer></script> <link rel="stylesheet" href="{% static 'myProject/CSS/checkStyle.css' %}"> <link rel="stylesheet" href="{% static 'myProject/CSS/datatables.min.css' %}"> </head> <table id="myTable"> <thead> <tr> <th>Head Value</th> <th>Another head Value</th> </tr> </thead> <tbody> {% for value in list_of_value %} <tr> <td><input type="number" id="amount{{ value.id }}" value="1"></td> <td><button onclick="check(value.id)">Check input box</button></td> </tr> {% endfor %} </tbody> </table> And the JS like this: function check(value_id){ const amount= document.getElementById("amount"+wallet_id); console.debug(amount); } In the console all i get is "null" as if it doesn't exist but i tried modifying it with CSS and it worked just fine. I also tried using jQuery as so: function check(value_id){ var actionTable = $("#amount" + value_id +""); console.debug(actionTable); console.debug(actionTable.value); } And on this one i don't get a null i get an object: Object { } <prototype>: Object { jquery: "3.7.1", constructor: … -
Why does Django not hot-reload on M1 Mac?
I have a Django application. Back when I was using an Intel mac, it's hot-reloading functionality was working. However, a year ago I switched to one of the new Macs and now I can't get it to hot-reload. Here is my settings.py: import os import firebase_admin BASE_DIR = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY_1 = '12312312' # ... some more secret keys DISABLE_SERVER_SIDE_CURSORS = True DEBUG = True AUTH_USER_MODEL = 'my_project.MyUser' ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_project', ] MIDDLEWARE = [ 'django.middleware.gzip.GZipMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'my_project/'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'user', 'USER': 'user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', }, 'replica': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'user', 'USER': 'user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', }, } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' … -
Can't une checkout session in Stripe sandbox
I'm trying to set a stripe payment on my django app. I use a stripe sandbox to run some tests, and I'm following the tutorial. The view: @csrf_exempt @require_http_methods(["POST"]) def create_checkout_session(request): domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = '2025-03-31.basil' try: # ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param checkout_session = stripe.checkout.Session.create( ui_mode = 'custom', line_items=[ { 'price': 'price_1REvRjPI8ecN8OJKIS8uPTSJ', 'quantity': 1, }, ], currency="eur", mode='payment', # success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', # cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], return_url=domain_url + '/return.html?session_id={CHECKOUT_SESSION_ID}', ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) On client side: async function initStripe() { const stripe = Stripe(stripePk); const fetchClientSecret = () => fetch("/create-checkout-session/", { method: "POST", headers: { "Content-Type": "application/json" }, }) .then((r) => r.json()) .then((r) => {console.log(r); return r.sessionId}); const appearance = { theme: 'stripe', }; checkout = await stripe.initCheckout({ fetchClientSecret, elementsOptions: { appearance }, }); ... }); I have <script src="https://js.stripe.com/basil/stripe.js"></script> on my html checkout page. Issue: when I'm on the checkout page and initStripe is launched, I get this error: Uncaught (in promise) IntegrationError: Invalid client secret. The resolved value returned from `fetchClientSecret` should be a client secret of the form ${cs_id}_secret_${secret}. But the value received was: cs_test_a1Ybi... … -
Django template loader looking at an old installed_apps list from settings.py
I have Django 5.2 installed. I had an app named 'home' in my installed_apps list in settings.py. I renamed the app to 'core' and did a full refactor. Now, Django is loading the views from the 'core' app, but for some reason, the template loader is still looking in 'home/templates/home/homepage.html'. It is somehow still using the installed_apps list from the previous settings.py. Does anyone have any idea why this is happening? -
I can't find the cause for a 405 error in my POST method
I am working on a form using the Django framework and I keep getting a 405 error which I can't seem to fix. I have an html template which contains a form allowing admins to add new TAs to the database accountAdd.html <html lang="en"> <head> <meta charset="UTF-8"> <title>Edit Courses</title> <style> body { font-family: Arial, sans-serif; padding: 2rem; background-color: #f4f4f4; } .container { max-width: 600px; margin: auto; background: #fff; padding: 2rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); } h1 { text-align: center; margin-bottom: 1.5rem; } label { display: block; margin-bottom: 0.5rem; font-weight: bold; } select { width: 100%; padding: 0.5rem; margin-bottom: 1rem; border: 1px solid #ccc; border-radius: 4px; } .button-group { display: flex; justify-content: space-between; } button { background-color: #333; color: #fff; padding: 0.5rem 1.5rem; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #555; } </style> </head> <body> <center> <div class="container"> <h1>Add Account</h1> {% if submitted%} TA added succesfully {% else %} <form action ="" method=POST> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> {% endif %} </div> </center> </body> </html> Views.py (relevant method and imports only) from django.shortcuts import render from django.views import View from .models import * from .forms import * from django.http import HttpResponseRedirect class accountAdd(View): def … -
drf-standardized-errors not generating 404 for RetrieveAPIView
The documentation for drf-standardized-errors says that it can be integrated with DRF-Spectacular and will generate error response documentation. It specifically provides instructions on how to "Hide error responses that show in every operation", e.g. standard 404 or 401 responses. But I haven't been able to generate 404 error responses for standard DRF views, e.g. RetrieveAPIView: class MemberDetailsView(generics.RetrieveAPIView): serializer_class = MemberDetailsSerializer schema = AutoSchema() def get_queryset(self): member_id = self.kwargs["pk"] cache_key = f"member_{member_id}" cached_member = cache.get(cache_key) if cached_member is None: print("NO CACHE") cached_member = TE_MemberList.objects.filter(id=self.kwargs["pk"]) cache.set(cache_key, cached_member, timeout=600) return cached_member It only generates a 200 response. I've looked into the code of drf-standardized-errors AutoSchema, and noticed that it calls get_response_serializers() method of drf-spectacular AutoSchema, which does not have a 404 code among the responses. If I have something like raise NotFound(detail="Object not found") in a view, then it does generate a 404 response documentation. Am I misunderstanding the purpose of this auto-integration? -
Error "Couldn't import Django" running MS Visual Code Tutorial
I am a newbie to coding and MS Visual Studio Code and trying to learn Django using MS Visual Studio Code (VCS) tutorial: https://code.visualstudio.com/docs/python/tutorial-django on a Dell XPS running Windows11 Home. I have successfully completed the first section to get Django running from VSC using: Terminal Window: python manage.py runserver Edge Browser: http://127.0.0.1:8000/ The Browser displays: Hello, Django! Then I try to use the VCS debugger and get the following error: Exception has occurred: 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? File "C:\Users\Mark\Dropbox\Coding\Udemy\ToDo\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: File "C:\Users\Mark\Dropbox\Coding\Udemy\ToDo\manage.py", line 13, in main "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?" ) from exc execute_from_command_line(sys.argv) File "C:\Users\Mark\Dropbox\Coding\Udemy\ToDo\manage.py", line 22, in main() 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 created a launch.json file using the following options: Python … -
Can't add a field with an election
I'm student. Please don't scold me. models.py: from django.db import models class Teacher(models.Model): MATH = 'MT' PHYS = 'PH' COMP = 'CS' SUBJECTS_TEACHER_CHOICES = { MATH: 'Math', PHYS: 'Phys', COMP: 'Comp', } subjects = models.CharField( max_length=2, choices=SUBJECTS_TEACHER_CHOICES, default=MATH, ) first_name = models.CharField(max_length=128) error: ERRORS: TeachersApp.Teacher.subjects: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. I want to add a field with choices. -
How to implement images relationship with Abstract model in Django?
I'm working on a Django project where I have an abstract Post model that serves as a base for two concrete models: RentalPost and RoomSeekingPost. Both of these post types need to have multiple images. Here's my current model structure: class Post(BaseModel): title = models.CharField(max_length=256) content = models.TextField(null=True) status = models.CharField(max_length=10, choices=Status, default=Status.PENDING) class Meta: abstract = True class RentalPost(Post): landlord = models.ForeignKey("accounts.User", on_delete=models.CASCADE) # other fields specific to rental posts class RoomSeekingPost(Post): tenant = models.ForeignKey("accounts.User", on_delete=models.CASCADE) # other fields specific to room seeking posts I want to add image functionality to both post types. Ideally, I'd like to define the image relationship in the abstract Post model since both child models need this functionality. However, I understand that Django doesn't allow ForeignKey or ManyToMany relationships in abstract models because they can't be properly resolved without a concrete table. I've considered: Duplicating the image relationship in both concrete models (seems redundant) Using generic relations (I not like this approach) What's the recommended approach for handling this kind of situation where multiple concrete models inheriting from an abstract base need the same relationship? -
Implementation of django-allauth-ui==1.6.1 in the project
I'm trying to get through the tutorial https://www.youtube.com/watch?v=WbNNESIxJnY&t=499s. At 4:17:26 the author implements the django-allauth-ui library into the project. The tutorial is from 10 months ago and currently the latest version of this library requires the use of the slippers library. I followed the README file (https://github.com/danihodovic/django-allauth-ui/blob/master/README.md). I installed django-allauth-ui, django-widget-tweaks, slippers libraries. I added the apps to settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'commando', 'visits', # Third-party-apps "allauth_ui", 'allauth', 'allauth.account', 'allauth.socialaccount', "widget_tweaks", "slippers", ] I run command python manage.py collectstatic After using the command runserver I get a warning: WARNINGS: ?: (slippers.E001) Slippers was unable to find a components.yaml file. HINT: Make sure it's in a root template directory. So I created a components.yaml file in the templates folder src/ ├── templates/ │ ├── components.yaml with code: components: {} Warning disappeared but templates are not loading: Page How to implement the latest version of the library into the project to make it work like in the tutorial? -
Is it possible to use Django Admin's sortable list in my own app?
The Django Admin interface displays tables in sortable lists, where the columns are clickable to change the sort order. Is it possible to use this type of list view in my own code? I want to display a list and make it sortable like this, but I don't want to expose the admin interface to my users. I've tried django-sortable-listview, but it's not well maintained and doesn't quite do what I want. Suggestions of other third-party modules also very welcome! I'm just trying desperately not to reinvent the wheel. -
How can I efficiently perform symbolic and numerical tensor computations in a Python web app using Django and SymPy
I'm building a scientific web tool that allows users to input custom spacetime metrics and compute geometric quantities from general relativity — including Christoffel symbols, Ricci, Einstein, and Weyl tensors. The backend is built in Python using Django, and I’m using SymPy for symbolic computation. I'm also working on a separate C-based module for ray-tracing visualizations of curved spacetime, which may be called through bindings later. Right now, the frontend is ready and deployed, but the backend (which handles heavy symbolic calculations) is not hosted yet due to cost constraints. I’d like to understand the best architecture and optimization strategies for when I do host it. My main challenges: Performance: SymPy can get slow with complex metrics. Are there any best practices to cache or optimize repeated tensor computations? Deployment: Would you recommend platforms like Render, Fly.io, or Railway for a Django app with heavier symbolic loads? Is there a better approach to split symbolic and numerical parts to make them more efficient/scalable? Any security concerns when exposing symbolic input processing to the public? This is part of an open project I’ve been working on solo. Here's the frontend version: https://itensor.online Docs: https://itensor-docs.com Backend source: https://github.com/Klaudiusz321/Tensor-backend-calculator Would appreciate any advice … -
100% CPU utilization on EC2
My EC2 instance has been crashed by periods of 100% utilization twice during the last 2 days and I am trying to figure out what is happening here. As you can see in the image below there were two plateaus of 100% CPU usage (the subsequent spike is me rebooting the instance). This started happening after I started running a Django server on the instance. Prior to that, I had an Express.js server running there with no issues. My Django server is being hosted by apache with mod_wsgi. I checked the access and error logs for apache and there seems to be nothing weird going on - all the activity is from me playing around and the occasional bot. Where should I start investigating? -
Django multi-table-inheritance + django-model-utils query optimization
I have some troubles to optimize ManyToManyField in child model with concrete inheritance. Assume I have models: class CoreModel(models.Model): parent = ForeignKey(Parent) class Parent(models.Model): pass @cached_property def child(self): return Parent.objects.get_subclass(pk=self.pk) class ChildA(Parent): many = ManyToManyField(SomeModel) class ChildB(Parent): many = ManyToManyField(SomeModel) In template I make a call: {% for m in parent.child.many.all %} {{ m.title }} {% endfor %} And this performs extra query for each instance. In my view I've tried to optimize in this way : core_instance = CoreModel.objects.prefetch_related( Prefetch( "parent", queryset=Parent.objects.select_subclasses()\ .prefetch_related("many") ) However I'm getting error: ValueError: Cannot query ChildAObject(some_pk). Must be "ChildB" instance. As I understand select_subclasses() "converts" parent class into child class. Both child classes have same field but still getting error. What I'm missing? -
How to restrict a foreign key form field based on previously selected field?
To preface this I know that there are some previous posts about this but the answers refer to using 3rd party packages and I was wondering if there is a solution using vanilla Django as these posts are a few years old. I am creating an music based app which has models for Artists, Albums and Tracks. What I'd like to do is when adding new tracks in the admin panel, if I select an Artist in the form then the Album choices are restricted to ones by that Artist but can't find anyway to make this work, at first I thought I may have been able to use "__" to make the relation, like in list_filter for the model admin but that didn't work. I added the artist field to the Track while trying to find a solution for this but am unsure if it is required. I am yet to develop most of the views for this app, this is currently just for the admin panel to add new tracks. class Artist(models.Model): name = models.CharField(max_length=100, verbose_name="Artist") genre = models.CharField(max_length=100) country = CountryField(blank_label="(select country)") is_approved = models.BooleanField(default=False) def __str__(self): return self.name class Album(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = … -
Django ORM, append external field to QuerySet
I have a simple queryset resulting from this: Books.objects.all() Books is related to Authors like this: Class Books: ... author = models.ForeignKey(Authors, on_delete=models.CASCADE) Class Authors: id = models.AutoField(primary_key=True) name = models.CharField() So for each book there's only one author. I want to add to each instance of the Books queryset the related Author 's name, as in this query: SELECT a.*, b.name FROM Books as a JOIN Authors as b on a.author_id = b.id I tried to read the documentation on Annonate or the selected_related method but didn't find a solution. -
Uncaught runtime errors: × ERROR (TypeError) + initStripe
Uncaught runtime errors: × ERROR Cannot read properties of undefined (reading 'match') TypeError: Cannot read properties of undefined (reading 'match') at initStripe (http://localhost:3000/static/js/bundle.js:41222:22) at http://localhost:3000/static/js/bundle.js:41264:12 I tried: analyzing the stack trace and understanding how .match() works. I expected: that a variable you assumed was a string wasn’t actually defined at runtime. -
Celery keeps throwing an error when I run my workers with --pool gevent or eventlet but works fine without these pools specified
I have a celery task like so: from celery import Celery from asgiref.sync import async_to_sync from celery_app.celery_commands import some_async_command import os redis_connection_string = os.environ.get("REDIS_URL") celery_app = Celery( 'tasks', backend=f"{redis_connection_string}/0", broker=f"{redis_connection_string}/1") @celery_app.task() def sample_task(**kwargs): result = async_to_sync(some_async_command)(**kwargs) return result When I use run celery for this task with : celery -A celery_app.tasks worker --loglevel=INFO -n my_app_worker --concurrency=4, it works fine. However, since the async function some_async_command is mainly I/O-bound and makes calls to the network, I was considering using gevent pool. I have installed gevent, but when I run celery -A celery_app.tasks worker --loglevel=INFO -n my_app_worker --concurrency=4 --pool gevent, it throws the error: Usage: celery [OPTIONS] COMMAND [ARGS]... Try 'celery --help' for help. Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'select' has no attribute 'epoll' What am I missing?