Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to extract data from queryset with django filter
yes_limit = Yes_Limitorder_Quantity.objects.filter(event_id = id) Yes_limit = {"yes_amount1":1, "yes_amount2":4, "yes_amount3" : 0, "yes_amount4":2, "yes_amount5":0} I'm using filter following data me expected: Yes_Limit = {"yes_amount1":1, "yes_amount2":4,"yes_amount4":2} -
Why do I keep getting an 'object of type method has no len()' error when using Django's pagination?
Been trying to figure out why do I keep getting *"object of type 'method' has no len()", where it directs me to this line. Please help I've been at it for the past 3 days and i really want to pull my hair out. from django.core.paginator import Paginator def index(request): allPosts = Post.objects.all().order_by("id").reverse #paginator paginator = Paginator(allPosts, 10) page_number = request.GET.get('page') *posts_of_page = paginator.get_page(page_number)* return render(request, "network/index.html", { "allPosts" : allPosts, "posts_of_page" : posts_of_page, }) -
How To Run Discord bot inside Django and use signals with it
So I have created my django website and. I want to run my discord bot inside my django website And also **can I use the signals to send a message on my server if post have been crated ** So any one can help me how to do that -
Default content-type for Django test client
I am trying to make application/json the default content type of the Django test client. I am wondering if there is a smarter way than this: from functools import partial c = Client() c.post = partial(c.post, content_type="application/json") I tried Client(content_type="application/json") and Client(HTTP_CONTENT_TYPE="application/json") but neither of them worked. -
How to fix bug when multiple accordions open in Bootstrap when quickly switching between them?
I'm trying to implement an accordion using bootstrap, where when a button is clicked, a collapse show occurs. It is important to understand that when one collapse is opened, the other must be closed. And it seems to work that way, but if I start switching between them quickly, I catch a bug where I have two collapse open at the same time. The Bootstrap documentation says that to achieve this effect, you need to specify the same data-bs-target, but as you can see from my code, this aspect is taken into account. Below I will attach all the required code, as well as a video with a demonstration of this bug. HTML <div class="container"> <div class="accordion" id="accordion"> <div class="steps"> <div class="step-item mx-auto"> {% for step in steps %} {% if step.id == 1%} <button class="step-button text-center" type="button" data-bs-toggle="collapse" data-bs-target="#Step{{ step.id }}" aria-expanded="true" aria-controls="collapse{{ step.id }}"> {{ step.id }} </button> {% else %} <button class="step-button text-center" type="button" data-bs-toggle="collapse" data-bs-target="#Step{{ step.id }}" aria-expanded="false" aria-controls="collapse{{ step.id }}" > {{ step.number_step }} </button> {% endif %} {% endfor %} </div> </div> <div class="card "> {% for step in steps %} {% if step.id == 1 %} <div id="Step{{ step.id }}" class="collapse show" data-bs-parent="#accordion"> … -
HTMX does not send new values in select
I'm using htmx and django-filter and i want to change with hx-get and hx-target another select values but instead i got blank options in select template.html {% render_field form.open_point_object class='form-select' hx-get='/customer/open-point-list/' hx-target='#id_category_choice' %} {% render_field form.category_choice|add_class:'form-control' %} urls.py path('customer/presence-info/', CustomerPresenceInfoList.as_view(), name='customer_presence_info'), filters.py def qsCategory(request): object = request.GET.get('open_point_object') if object: return OpenPointList.objects.filter(open_point_object=object).values_list('category', flat=True).distinct() return OpenPointList.objects.values_list('category', flat=True).distinct() class OpenPointFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['category_choice'].extra['choices'] = [ (category, category) for category in qsCategory(request=self.request) ] after changing value in open_point_object i got this in category_choice select -
Is there a way to process values passed from React in django and then send them back to React?
I'm cooperating with my friend to make toy project using Django RESTful api and React. I'm doing with django. This is my simplified model.py: class Map(models.Model): name = models.CharField(max_length=50) monsters = models.ManyToManyField('Monster', blank=True, related_name='maps') def __str__(self): return self.name class Quest(models.Model): name = models.CharField(max_length=50) goal = models.TextField() recommended_map = models.ManyToManyField(Map, related_name='quests') def __str__(self): return self.name I completed to pass quest list to react side using api. Users can select several quests from that list. What I want to do is finding a recommened_map that the user selected quest has in common and sending it back to React. I've searched all day but I couldn't. Is it impossible? -
How to make Django present generated mp4
I have a docker volume that contains generated mp4 files. I want to find a way to display them in dev because my current solution results in an error. error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/fergana_api/files/36/movies/movie.mp4 Using the URLconf defined in fergana_api.urls, Django tried these URL patterns, in this order: admin/ api/schema/ [name='api-schema'] api/docs/ [name='api-docs'] api/ [name='all-runs'] tests/<slug:test_session_id> [name='single-run'] tests/<slug:test_session_id>/<slug:test_name> [name='single-test'] ^static/(?P<path>.*)$ ^files/(?P<path>.*)$ The current path, fergana_api/files/36/movies/movie.mp4, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. settings.py STATIC_URL = 'static/' MEDIA_URL = 'files/' MEDIA_ROOT = '/var/web/media/' STATIC_ROOT = BASE_DIR / 'static_files' # location of static files STATICFILES_DIRS = [ BASE_DIR / 'static' ] app/views.py class SingleTestView(View): def get(self, request, test_session_id, test_name): run = Runner.objects.get(id=test_session_id) path_to_session = to_file('files/', f'{test_session_id}') movies_dir_path = to_file(path_to_session, 'movies') movie_path = to_file(movies_dir_path, test_name.replace('-', '_') + '.mp4') context = { 'movie_path': movie_path } return render(request, "presenter/single_test.html", context) project/url.py if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) single_test.html <video width="320" height="240" controls> <source src="{{ movie_path }}" type="video/mp4"> </video> It seems like the app uses the correct … -
Access Data in the Template from the Junction Model
I´m Trying to Access Data from my "junction" model clientvul in my Template. models.py from django.db import models from django.contrib import admin class client(models.Model): client= models.CharField(max_length=50,primary_key=True) user= models.CharField(max_length=100) vuls = models.ManyToManyField( 'vul', through='clientvul', related_name='client' ) class vul(models.Model): vid=models.IntegerField(primary_key=True) cvelist=models.CharField(max_length=50) cvsscore=models.FloatField(max_length=5) serverity=models.CharField(max_length=25) title=models.CharField(max_length=1000) summary=models.CharField(max_length=1000) class clientvul(models.Model): client= models.ForeignKey(client, on_delete=models.CASCADE) vid=models.ForeignKey(vul, on_delete=models.CASCADE) path=models.CharField(max_length=1000) isactive=models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint( fields=['client', 'vid'], name='unique_migration_host_combination' ) ] admin.site.register(client) admin.site.register(vul) admin.site.register(clientvul) views.py def index(request): qs = client.objects.prefetch_related('vuls') return render(request, 'browseDB.html', {'data':qs}) Template {% for row in data %} <table class="table"> <thead class="table-dark"> <tr> <th scope="col">Hostname</th> <th scope="col">User</th> </tr> </thead> <tbody> <td class="Hostname">{{ row.client }}</a></td> <td class="User">{{ row.user }}</td> </tbody> </table> <table class="table"> <thead> <tr> <th scope="col">Title</th> <th scope="col">Severity</th> <th scope="col">CVE</th> <th scope="col">Path</th> </tr> </thead> <tbody> {% for subitem in row.vuls.all %} <tr> <td class="Title" >{{ subitem.title }}</td> <td class="Severity">{{ subitem.serverity }}</td> <td class="CVE" >{{ subitem.cvelist }}</td> <td class="Path" >{{ subitem.path }}</td> </tr> {% endfor %} </tbody> </table> <br> {% endfor %} The problem is that <td class="Path" >{{ subitem.path }}</td> stays empty. I don´t know how I can reference the related path from the junction Model clientvul. Related Question: Django prefetch_related with 3 not directly related Models -
Django test counting queries is failing because of SQL EXPLAIN queries
I have a test like this: from django.test import TestCase class MyTestClass(TestCase): def test_query_count(self): with self.assertNumQueries(12): some_service_call() When running tests using pytest I get an error saying that there were 24 queries instead of 12 and when checking the logged error I see that I have one EXPLAIN query per real query made by some_service_call(). This is not happening with plain django test runner (i.e: python manage.py test). Does anyone know why I'm getting these explain queries and how can I avoid getting them when testing? I'm using the official postgresql docker image. Weird thing is that when I run using pytest for that file (i.e: pytest path/to/test.py) I don't have this issue. -
How can I ensure that transaction.atomic() uses the default database for both read and write queries in Django?
This is my router,to ensure read-write separation. class Router(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ return 'readonly' def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ return 'default' but when using transaction.atomic(), I need to use the default db for all read and write queries. One way to do this is to use using to specify the default library for all read queries, but this is cumbersome and I need to check the query in each transaction. Is there any other better plan? with transaction.atomic(): # create some objs MyModel.objects.create(name='tom', **data) # do something # query count = MyModel.objects.using('default').filter(name='tom').count() -
In django, how to make ansible_runner pass the output to the page through websocket
I want to display the output similar to the following on the page in real time, or save it to the database after being captured. I think ansible_runner should have such an interface, but I can't find it Tuesday 30 May 2023 08:45:30 +0800 (0:00:00.059) 0:00:00.059 *********** 12.212.212.22 | SUCCESS => { "ansible_facts": { "ansible_memfree_mb": 258388, "ansible_memtotal_mb": 515659, "discovered_interpreter_python": "/usr/bin/python" }, "changed": false } Tuesday 30 May 2023 08:45:33 +0800 (0:00:02.731) 0:00:02.790 *********** =============================================================================== setup ------------------------------------------------------------------- 2.73s -
My Django website doesn't update HTML and CSS code
I'm building Django website and when I wrote HTML code and reload the page, it didn't make anychanges and when I tried to change the background color to red, it didn't chnaged, even when I deleted all my code in HTML file, website stayed the same. Usually in these situations I click inspect then left click on reload button and click "Empty Cash and Hard Reload", but this time it didn't work, and I tried ctrl + F5, and shift + F5 but it still didn't work. -
Django hosted with cPanel crashes shortly after I change an object in models
I am working on a react-native app with Django backend. I recently deployed the Django app with cPanel. When I do an action in the app that updates or makes an object in models and then I do something that requires a lot of processing (make matches between some users which uses a probability based ai and then some "GET" methods for images stored on the app) it causes the domain to crash for about 30 seconds and then it works again. This problem does not happen when I try running the Django app through my computer (not deployed). This part is very important for the rest of my project. Is there something I can do to fix this problem? Should I consider deploying it on something other than cPanel? -
How to display a 3D object (*.stl file) using Django
I have a website developed using Django. Several 3D object files (*.stl files) are loaded from the administration. I would like to add the following two functionalities. 1- Being able to view 3D objects, both for an administrator and for a regular user. 2- In case of being a regular user, the object is only downloadable, under some conditions (for example if the user pay for the article.) The following site is a good benchmark of what I want. sketchfab I don't even know how to proceed, any comment would be welcome. -
What are the steps to integrate a Javascript framework (like React or Svelte) into a Django app for stat tracking purposes?
I've been working on a web app using Django that will track stats for an intramural league I'm involved in. I have just about all the models I need and I'm slowly putting together the views I need as I learn Django and develop this app. I want to create a page in my web app that will serve as a stat tracker for my league. Essentially, you could have one or two people on the sidelines watching a game, while recording stats for said game on this webpage as the game goes on. I'd like to use a Javascript front-end framework for just this page. I'd also like to be able to just plug it in to the Django app I already have without remaking the whole thing. I know of a few JS frameworks (React, Vue, Svelte), but I've only done as much as go through the interactive React tutorial. Long story short, I know next to nothing about JS frameworks. I do know a little bit about Javascript though. How would I plug in a Javascript framework to create this webpage for taking stats? What JS frameworks would you recommend I use? I like the look of … -
Error running Django and Ghost in Docker Compose: 'manage.py' file not found and database access denied
I'm trying to set up a Docker Compose configuration to run Django and Ghost together, but I'm encountering some issues. Here are the relevant files: dockerfile: FROM python:3.12-rc-bullseye WORKDIR /django_dir COPY requirements.txt . RUN pip install -r requirements.txt COPY . /django_dir docker-compose.yml: version: '3.1' services: db: image: mysql:8.0 restart: always environment: MYSQL_USER: example MYSQL_PASSWORD: example MYSQL_ROOT_PASSWORD: example volumes: - ./mysql_dir:/var/lib/mysql networks: - nginx ghost: image: ghost:latest restart: always ports: - 2368:2368 environment: database__client: mysql database__connection__host: db database__connection__user: example database__connection__password: example database__connection__database: ghost url: https://example.com.br volumes: - ./ghost_dir:/var/lib/ghost/content networks: - nginx depends_on: - db django: build: context: . dockerfile: dockerfile restart: always ports: - 8000:8000 environment: - DEBUG=1 command: python /django_dir/manage.py runserver 0.0.0.0:8000 networks: - nginx volumes: - ./django_dir:/django_dir networks: nginx: name: nginx-proxy external: true When I run docker-compose up, I'm getting the following errors: For the Django service: python: can't open file '/django_dir/manage.py': [Errno 2] No such file or directory For the Ghost service: Access denied for user 'example'@'172.18.0.4' (using password: YES) I have checked the file paths and database credentials, but I can't seem to find a solution. What could be causing these errors? How can I fix them? Any help or suggestions would be greatly appreciated. Thank you! -
Retrieving data from an Excel file in Django using Pandas: How can I include duplicates that are being overwritten by Python?
I am creating a django application which retrieves data from an excel file. The excel file I access the excel file through the scrape.py file: import pandas as pd import os from pathlib import Path BASE_DIR = Path(file).resolve().parent DATA_DIR = os.path.join(BASE_DIR, "Data") database_path = os.path.join(DATA_DIR, "Data.xlsx") Database = pd.read_excel(database_path) Then I have this class: class skimask: def init(self, name, GradesWDates, motive, avgGrade, highestgrade, pfp, nexttest, recentgrades, tens): self.name = name self.GradesWDates = GradesWDates self.motive = motive self.avgGrade = avgGrade self.highestgrade = highestgrade self.pfp = pfp self.nexttest = nexttest self.recentgrades = recentgrades self.tens = tens self.subjects = {} Evan = skimask('Evan', dict(zip(Database.Evan, Database.Date)), "B", 0, 0, "./static/media/evan1.png", list(Database.EvanNext), [], 0) Felix = skimask('Felix', dict(zip(Database.Felix, Database.Date)), "B+", 0, 0, "./static/media/felix.png", list(Database.FelixNext), [], 0) Hessel = skimask('Hessel', dict(zip(Database.Hessel, Database.Date)), "A+", 0, 0, "./static/media/hessel2.png", list(Database.HesselNext), [], 0) Niels = skimask('Niels', dict(zip(Database.Niels, Database.Date)), "B", 0, 0, "./static/media/niels.png", list(Database.NielsNext), [], 0) Sem = skimask('Sem', dict(zip(Database.Sem, Database.Date)), "A", 0, 0, "./static/media/sem1.png", list(Database.SemNext), [], 0) Students = [Evan, Felix, Hessel, Niels, Sem] This excel file is a file of all our grades of this year, and coincidentally there are duplicates, ofcourse. But python, for some reason, overwrites duplicates and skips over them. But I want to include those … -
How To Get Nginx Client Ip Using Revese Proxy (Django, Nginx)
I'm facing an issue with retrieving the client IP addresses from the X-Forwarded-For header when using Nginx as a reverse proxy server in front of my Django application. Currently, I'm only able to obtain the IP address of the Nginx proxy server instead of the actual client's IP. I have configured Nginx to set the necessary headers using the following directives: server { server_name example.domain.com; set_real_ip_from 0.0.0.0/0; real_ip_header X-Forwarded-For; real_ip_recursive on; location /static/ { root /home/user/example.domain.com/djangoapp; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://10.0.0.122:8000; } } I have tried it all, even using the map from this artlcle and alot more: link but the X-Forwarded-For and X-Real-IP are still the proxy server's IP and not the client IP! can't even get it to return a list and not just the last IP... In my Django view, I'm trying to access the client IP using request.META.get('HTTP_X_REAL_IP') and request.META.get('REMOTE_ADDR'). The headers are showing, but not the client's IP. { 'Content-Length': '', 'Content-Type': 'text/plain', 'X-Real-Ip': '10.0.0.101', 'X-Forwarded-Proto': 'https', 'X-Forwarded-For': '10.0.0.101', 'User-Agent': 'Mozilla/5.0 ...', even the user agenst is correct. but the IPs are not. I have also checked that the X-Forwarded-For header is … -
testdriven.io The Definitive Guide to Celery and Django getting error while tring submitting the form
The Definitive Guide to Celery and Django web sockets not working Hi, I've followed Django Channels and Celery chapter in The definitive guide to Celery and Django chapter and got the following error when I'm filling the form and press submit buttom: WebSocket connection to 'ws://localhost:8010/ws/task_status/d4e6e4e5-4000-4341-9e6d-15d1ded308e2/' failed: updateProgress @ (index):59 (anonymous) @ (index):111 I've reviewed the web app docker container logs and found the following: [29/May/2023 19:45:21] "GET /ws/task_status/e96dcec6-35f6-47f3-b55c-7379779fdeb9/ HTTP/1.1" 404 3122 [29/May/2023 19:49:44] "GET /form_ws/ HTTP/1.1" 200 4351 [29/May/2023 19:49:52] "POST /form_ws/ HTTP/1.1" 200 51 Not Found: /ws/task_status/d4e6e4e5-4000-4341-9e6d-15d1ded308e2/ But I still can't understand what's gone wrong. -
instance.save() method not updating the instance in the database
I have written this code for product checkout. I wanted to create a Order model and then update the transaction ID. But it's not getting updated, doesn't even providing any error. Whats's the issue ? @csrf_exempt @user_passes_test(lambda u: u.is_authenticated and not u.is_analyst) def processOrder(request): data = json.loads(request.body) transaction_id = datetime.now().timestamp() print(int(transaction_id)) if request.user.is_authenticated: customer = Customer.objects.get(user=request.user) order, created = Order.objects.get_or_create( customer=customer, complete=False) total = int(data['form']['total']) try: order.transaction_id = int(transaction_id) except Exception as e: print(e) order.complete = True print(order.transaction_id) try: order.save() except Exception as e: print(e) Here is my Order model that I've used. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) date_ordered = models.DateField(default="2014-02-20") complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) @property def shipping(self): shipping = False order_items = self.orderitem_set.all() for i in order_items: shipping = True return shipping @property def get_cart_total(self): order_items = self.orderitem_set.all() total = sum([item.get_total for item in order_items]) return total @property def get_cart_items(self): order_items = self.orderitem_set.all() total = sum([item.quantity for item in order_items]) return total def __str__(self) -> str: return str(self.id) -
What is going on with my Django site, it's health check, and admin page? [closed]
I'm following a Django tutorial located here: https://dev.to/daiquiri_team/deploying-django-application-on-aws-with-terraform-minimal-working-setup-587g I successfully made it to step 4 located here: https://dev.to/daiquiri_team/deploying-django-application-on-aws-with-terraform-namecheap-domain-ssl-19a5 During Step 4, the author writes the following: I was able to receive Healthy! from the 127.0.0.1:8000/health url. Also, at one point I was able to get Bad Request from my equivalent Load Balancer domain, however I destoryed and rebuilt the underlying infrastructure, and now I get Not Found from both the AWS Load Balancer domain and the /health/ check, however the /admin/ page successfully loads and allows me to login (although I did not attempt to login). Could someone help explain what is going on? I'd like the AWS Load Balancer page to load Bad Request, same with the /admin page I presume...but the Health check should show Healthy. Lastly, my custom domain isn't working any longer either. I'm assuming that is because of my infrastructure tear down and rebuild...it updates the name servers for DNS and I think they take a days to correct. -
TypeError in Django: "float () argument must be a string or a number, not 'tuple.'"
Description: When attempting to access a specific page that relate to a cryptocurrency, in this case Dogecoin, I receive a TypeError in my Django application. "Field 'bought_price' expected a number but got (0.07314770668745041,)" reads the error notice. The traceback also states that the problem is with the float() function and that a tuple was used as the argument. The passed value, however, is not a 'tuple'. It is a numpyfloat64 type, therefore I tried passing the same value after converting it to a float type in Python. Even if I provide the form a static value, the problem still occurs. form.instance.bought_at = 45.66 results in the same issue. Could anyone help me understand why this error is occurring and how I can resolve it? Here's the relevant code: Model Code: class Order(models.Model): coin = models.CharField(max_length=100) symbol = models.CharField(max_length=50) bought_price = models.FloatField() quantity = models.IntegerField(default=1) bought_at = models.DateTimeField(default=datetime.now) user = models.ForeignKey(User, on_delete=models.CASCADE) View Code: ticker = yf.Ticker(symbols[pk]) price_arr = ticker.history(period='1d')['Close'] price = np.array(price_arr)[0] if request.method == 'POST': form = BuyForm(request.POST) if form.is_valid(): form.instance.coin = ticker.info['name'], form.instance.symbol = ticker.info['symbol'], form.instance.bought_price = price, form.instance.user = request.user form.save() return redirect('portfolio') else: form = BuyForm() I appreciate any assistance or insights you can provide. Thank … -
How can I fix the error of not being able to establish a connection to a Django Channels server with WebSockets using Python and ASGI?
Django channels & websockets : can’t establish a connection to the server. I am trying to do a real-time drawing app using django channels, websockets & p5. The only problem I've got is : Firefox can’t establish a connection to the server at ws://XXX.XXX.XXX.XXX:8090/ws/room/1/. What I've done : settings.py : INSTALLED_APPS = [ ... 'channels', ] ASGI_APPLICATION = 'DrawMatch.asgi.application' CHANNEL_LAYERS = { 'default': { "BACKEND": "channels.layers.InMemoryChannelLayer" } } asgi.py : os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DrawMatch.settings') django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( drawmatch_app.routing.websocket_urlpatterns ) ) ), }) consumers.py : class DrawConsumer(AsyncJsonWebsocketConsumer): room_code: str = None room_group_name: str = None async def connect(self): self.room_code = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = f'room_{self.room_code}' print(f"room_code: {self.room_code}") print(f"room_group_name: {self.room_group_name}") await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data: str = None, _: Any = None) -> None: data = json.loads(text_data) await self.channel_layer.group_send( self.room_group_name, { 'type': 'draw', 'data': data } ) async def send_message(self, res): await self.send(text_data=json.dumps({ "payload": res })) routing.py : websocket_urlpatterns = [ url(r'^ws/room/(?P<room_code>\w+)/$', DrawConsumer.as_asgi()), ] views.py : def room(request, room_code): context = { 'room_code': room_code } return render(request, 'room.html', context) urls.py : urlpatterns = [ path('', views.home), ... path('room/<room_code>/', views.room), path('predict', draw_guess.main), … -
Celery task queue not blocking to single thread - what am I doing wrong?
I'm trying to reproduce example from Celery official Task Cookbook (link: Ensuring a task is only executed one at a time) and I can't figure out why my Celery task queue is not blocked to single thread. So here is my code snippet (it is almost exactly the same as in the official doc): from celery import shared_task from celery.utils.log import get_task_logger from django.core.cache import cache logger = get_task_logger(__name__) LOCK_EXPIRE = 60 * 10 @contextmanager def memcache_lock(lock_id, oid): timeout_at = time.monotonic() + LOCK_EXPIRE - 3 status = cache.add(lock_id, oid, LOCK_EXPIRE) try: yield status finally: if time.monotonic() < timeout_at and status: cache.delete(lock_id) @shared_task(bind=True, name="print_text") def print_text(self, text): text_hexdigest = md5(text.encode("utf-8")).hexdigest() lock_id = "{0}-lock-{1}".format(self.name, text_hexdigest) logger.debug("Printing text: %s", text) with memcache_lock(lock_id, self.app.oid) as acquired: if acquired: import time time.sleep(5) return logger.debug("Print_text %s is already being imported by another worker", text) When I call the print_text function several times, the first call should block the second (and all subsequent) calls - this is expected behavior: # ./manage.py shell from django_celery_example.celery import print_text task = print_text.delay('John') task = print_text.delay('John') But when I check the Celery output, both tasks run in parallel, without thread blocking (look at the time difference between the first and the …