Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django media images not loading in production using Nginx , with Debug=False
I'm deploying my Django project with DEBUG=False, and media files like images are not loading. Nginx Configuration server { listen 80; listen [::]:80; server_name <my_server_ip>; location /media/ { alias /home/ubuntu_server02/cdo_portal/media/; autoindex on; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Django settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') What are the details of your problem? I deployed my Django project with DEBUG=False, and I'm trying to serve uploaded media files (images) using Nginx. However, when I access a media file through the browser (e.g., http://<server_ip>/media/sample.jpg), I get a 404 Not Found error. The media files exist in the correct folder, Nginx is running, and permissions are correct. I'm not sure if the issue is with my Nginx config or something else. What did you try and what were you expecting? I tried accessing media files through the browser directly, like: http://<my_server_ip>/media/sample.jpg I expected the image to load, but it returned a 404. I checked that the file exists, the path in Nginx is correct, and the alias points to the right folder. Still, Nginx doesn't seem to serve the media files. -
django-mptt using get_root() on TreeQuerySet element inside for loop and output stored in list does not persist outside of for loop
I am trying to use get_root() on individual TreeQuerySet elements in a for loop. This seems to work in the Django Python shell as shown below. Upon pressing [Enter] twice to indicate the end of the for loop, the result of applying the get_root() to each element is printed automatically in the shell. The result is correct in that the output does indeed list the top level root of each TreeQuerySet element. However outside of the loop, the list in which these should be stored in is not updated. Instead this list contains the original TreeQuerySet elements. In Django Python shell: >>> topics_w_arttype_articles = topics.Topic.objects.filter(to_ArtTypeArticle_topic_from_Topic__title__isnull=False).distinct() >>> topics_w_arttype_articles <TreeQuerySet [<Topic: Level1Topic1>, <Topic: Level1Topic2>, <Topic: Level1Topic3>, <Topic: Level1Topic4>, <Topic: Level2Topic1>, <Topic: Level2Topic2>, <Topic: Level2Topic3>, <Topic: Level2Topic4>]> >>> arttype_topic_roots_list = [] >>> for item in topics_w_arttype_articles.iterator(): ... item.get_root() ... arttype_topic_roots_list.append(item) ... <Topic: Level0Topic1> <Topic: Level0Topic2> <Topic: Level0Topic2> <Topic: Level0Topic3> <Topic: Level0Topic4> <Topic: Level0Topic5> <Topic: Level0Topic5> <Topic: Level0Topic5> >>> arttype_topic_roots_list [<Topic: Level1Topic1>, <Topic: Level1Topic2>, <Topic: Level1Topic3>, <Topic: Level1Topic4>, <Topic: Level2Topic1>, <Topic: Level2Topic2>, <Topic: Level2Topic3>, <Topic: Level2Topic4>] >>> I placed the logic of the shell interaction in a custom template tag, shown below (with additional code that should remove duplicates from the list, if it … -
Why aren't my Django Postgres `ArrayAgg` members sorting?
I'm exploring the use of ArrayAgg and I don't understand why 'histidine-[13C6,15N3]' doesn't occur before 'isoleucine-[13C6,15N1]' in this example: In [25]: for i in Infusate.objects.annotate(tns=ArrayAgg("tracer_links__tracer__name", order_by="tracer_links__tracer__name")).order_by("tns").distinct(): ...: print(i.tns) ...: ['inosine-[15N4]'] ['isoleucine-[13C6,15N1]', 'leucine-[13C6,15N1]', 'valine-[13C5,15N1]'] ['isoleucine-[13C6,15N1]', 'lysine-[13C6,15N2]', 'phenylalanine-[13C9,15N1]', 'threonine-[13C4,15N1]', 'tryptophan-[13C11]', 'histidine-[13C6,15N3]'] The records/rows are sorted based on the first value, which is great, but that first value isn't sorted WRT the other values in the list. For that matter, why doesn't the order of the members of the list change at all when I negate the order_by in the ArrayAgg? According to what I read, this should sort the list items. Am I blind? What am I doing wrong? In [25]: for i in Infusate.objects.annotate(tns=ArrayAgg("tracer_links__tracer__name", order_by="-tracer_links__tracer__name")).order_by("tns").distinct(): ...: print(i.tns) ...: ['inosine-[15N4]'] ['isoleucine-[13C6,15N1]', 'leucine-[13C6,15N1]', 'valine-[13C5,15N1]'] ['isoleucine-[13C6,15N1]', 'lysine-[13C6,15N2]', 'phenylalanine-[13C9,15N1]', 'threonine-[13C4,15N1]', 'tryptophan-[13C11]', 'histidine-[13C6,15N3]'] -
Django, docker compose, whitenoise and railways: new js files not found in production (it works in local)
I am working in a django project where I have installed and configured whitenoise to serve static files in railways. But railways is not serving or collecting my new js files. In my browser I get a 404 in settings I have configured (theoretically) whitenoise INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'captcha', 'storages', 'whitenoise.runserver_nostatic', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and this is where I am managing my files (I am also using amazon aws s3 to upload pdfs and other files) STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" STORAGES = { "default": { "backend": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "whitenoise.storage.CompressedStaticFilesStorage", # CompressedStaticFilesStorage }, } # Modify storage configuration if ENV_STATE == "production": SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # HIPAA-compliant Backblaze configuration AWS_ACCESS_KEY_ID = os.environ['B2_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['B2_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['B2_BUCKET_NAME'] AWS_S3_ENDPOINT_URL = os.environ['B2_ENDPOINT_URL'] AWS_S3_REGION_NAME = os.environ.get('B2_REGION_NAME', 'us-west-004') # Default region # Security settings AWS_DEFAULT_ACL = 'private' # HIPAA: Private access only #AWS_LOCATION = 'protected' # This should match your prefix AWS_S3_FILE_OVERWRITE = False AWS_S3_ADDRESSING_STYLE = 'path' AWS_QUERYSTRING_AUTH = True # Enable signed URLs for HIPAA compliance AWS_QUERYSTRING_EXPIRE = 3600 … -
How can I display a table in a template with additional category/section rows?
Have a nice day! I have a non-standard table. Which I plan to display in the template. I load the table into the template from the model. And I have additional sections - additional fields. These additional fields characterize - Category, Section, Topics. I am thinking how to display such a table from the model in the template - as shown in the picture. To additionally implement additional fields - categories or sections in the table. I have a rough idea - I have to create a transit model for exactly such a table - in which the number of rows is equal to the number of rows of the original table + plus the number of rows of category sections in addition. That is, there can be about 25 rows of the original table and + plus 6 rows - category sections. In total, the required table will have 31 rows of rows. enter image description here But how to display them in the form as in my picture - separating categories sections? models.py class CreateNewGPR (models.Model): name_object = models.IntegerField(verbose_name="") name_category = models.CharField(verbose_name="") name_working = models.CharField(verbose_name="") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="") value_work = models.FloatField(verbose_name="") lyudi_norma = models.IntegerField(verbose_name="") technik_norma = models.IntegerField(verbose_name="") … -
How to support multiple Google Cloud Storage buckets in a Django FileField without breaking .url resolution?
I'm using Django with django-storages and GoogleCloudStorage backend. My model has a FileField like this: raw_file_gcp = models.FileField(storage=GoogleCloudStorage(bucket_name='videos-raw')) At runtime, I copy the file to a different bucket (e.g. 'videos-retention') using the GCS Python SDK: source_blob = default_bucket.blob(name) default_bucket.copy_blob(source_blob, retention_bucket, name) After copying, I update the .name field: recording.raw_file_gcp.name = f'videos-retention/{name}' recording.save() Everything works until I restart the app. Then, when I access .url, Django tries to build the URL using the original bucket from the storage=... argument, even if the file now belongs to another bucket. It ends up generating invalid URLs like: https://storage.googleapis.com/videos-raw/https%3A/storage.cloud.google.com/videos-retention/filename.mp4 I expected Django to keep working even if the file was moved to a different bucket. After debugging, I realized that the FileField is tightly coupled to the bucket used when the model is initialized. If the file moves to another bucket, .url breaks. ChatGPT suggested removing FileField altogether, using a CharField instead, and dynamically resolving the GCS bucket + path in a custom @property using google.cloud.storage.blob.generate_signed_url(). Is there a better solution for this? How can I support multiple GCS buckets dynamically with Django FileField? -
I tried to implement custom validation error in django
I have wrote this validators.py file: from django.core.exceptions import ValidationError import os def allow_only_images_validator(value): ext = os.path.splitext(value.name)[1] print(ext) valid_extensions = ['.png', '.jpg', '.jpeg'] if not ext.lower() in valid_extensions: raise ValidationError("Unsupported file extension. Allowed extensions: " +str(valid_extensions)) This is my forms.py file: class userProfileForm(forms.ModelForm): class Meta: profile_picture = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator]) cover_photo = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator]) But this error is not showing in my template. The SS is here: Can anybody help me on how do I fix it? -
In Django how can I list a Queryset in one view/template generated by another view?
I'm developing a tracking system that has 2 main datasets Orders and Shipments. Focussing on Orders I want to enable users to enter any combination of field data and then display the resulting list using pagination. To achieve this I have 2 views/templates. One, search_orders, displays a form that is, essentially, a list of the majority of the dataset fields. The other, list_orders, displays a list of the selected orders. This all works fine if I just render list_orders from search_orders without any pagination but, in order to get pagination I (believe that I) need search_orders to redirect to list_orders and, so far, I've been unable to do that. Search_orders view: @login_required def search_orders(request): if request.method == 'POST' and len(request.POST) > 1: orders = Order.objects.all() msg = '' fields_selected = '' for fld in request.POST: if fld == 'orderid' and request.POST.get('orderid'): msg += f'{fld} - {request.POST.get('orderid')} and ' fields_selected = True orders = orders.filter(orderid__icontains=request.POST.get('orderid')) if fld == 'bookingtype' and request.POST.get('bookingtype'): msg += f'{fld} - {request.POST.get('bookingtype')} and ' fields_selected = True orders = orders.filter(bookingtype__icontains=request.POST.get('bookingtype')) if fld == 'shp' and request.POST.get('shp'): msg += f'{fld} - {request.POST.get('shp')} and ' fields_selected = True orders = orders.filter(shp__icontains=request.POST.get('shp')) if fld == 'con' and request.POST.get('con'): msg += … -
How can I convert a QuerySet list to a list or a dataset for the choices field?
After doing some filters and operations, I write the data to the model. I get the data after processing in the model. Then I unload the data when displaying the form. There is a field in the form - which is like a choices field. But I'm not quite sure about the correct spelling for the form. My problem is that I can display the data for the choices field only after some processing or as a result of receiving data from another model. My task is to unload data from another model into the code. And then from the code send it to the choices field. How can I do something similar? models.py class Category_pk_for_form_maim (models.Model): categoty_name = models.CharField() def __str__(self): return self.categoty_name class Category_pk_for_form_category (models.Model): name_object = models.IntegerField(verbose_name="Наименование объекта") category_name = models.CharField() class CreateNewGPR (models.Model): name_object = models.IntegerField(verbose_name="Наименование объекта") name_category = models.CharField(verbose_name="Наименование категории/раздела/вида работ") name_working = models.CharField(verbose_name="Наименование работы") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="Единицы измерения") value_work = models.FloatField(verbose_name="Объём работ") lyudi_norma = models.IntegerField(verbose_name="Нормативные затраты персонала") technik_norma = models.IntegerField(verbose_name="Нормативные затраты техники") date_begin = models.DateField(verbose_name="Дата начала работ") date_end = models.DateField(verbose_name="Дата окончания работ") class GPRWorkingName (models.Model): name_working = models.CharField(verbose_name="Наименование работы по ГПР") def __str__(self): return self.name_working forms.py class Form_GPR (forms.ModelForm): class Meta: model = … -
invoice bill creation for the specific customers in billing software django forms
i am trying to create a invoice bill for the specific customer , first on the bill customer selection should be available for the selection of the customer , after that we are giving the option to add the items which are taken from the product app along with quantity input option . how can i implement this things using the django and dajngo forms i tried to do this but i am just able to implement the only customer selection option but not of items selection from the product i am giving the my codes of models.py form.py and views.py models.py: from django.db import models from customer.models import Customer from product.models import Product # Create your models here. class Invoice_customer_list(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) # date = models.DateField(auto_now_add=True) # total_amount = models.DecimalField(max_digits=10, decimal_places=2,default=0.00) def __str__(self): return f"Invoice # {self.id} -{self.customer.name}" class Invoice_product_list(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveBigIntegerField() forms.py: from django import forms from .models import Invoice_customer_list,Invoice_product_list,Product # Form for the Invoice model class Invoice_customer_Form(forms.ModelForm): class Meta: model = Invoice_customer_list fields = ['customer'] labels = { 'customer': 'Select Customer', } class Invoice_product_form(forms.ModelForm): class Meta: model = Invoice_product_list fields = ['product', 'quantity'] labels = { 'product':'Select Product', 'quantity':'Enter quantity', … -
Square Webhook doesn't give confirmation if the payment is done or not to Python-django
I'm encountering a critical issue where my Django backend is unable to receive confirmation from Square about whether a payment has been completed. Here are the environment details for reference: Python: 3.13.2 Django: 5.1.6 Square SDK: 43.0.0.20250618 Problem Summary: The core flow of the payment process is as follows: The user creates an order via the CreateSquareOrder method. This successfully generates a Square-hosted checkout page where the user completes the payment. The payment is processed correctly—I can confirm the funds are reaching my Square account. However, the issue arises after payment is completed: The webhook I’ve configured (https://api.mydomain.com/api/wallet/webhooks/square/) is supposed to be triggered automatically by Square to confirm the payment. Unfortunately, this webhook is not being triggered properly. I’ve checked the server logs, and I consistently receive a 401 Unauthorized response from Square's webhook call attempts. Because the webhook is failing, the subsequent logic in my Django app—specifically, the VerifySquareOrder method—is not executed, meaning critical application records are never created. Additional Information: Below is the backend code I’m currently using to handle CreateSquareOrder, SquareWebhookView and VerifySquareOrder requests. I’ve followed the latest version guidelines and best practices as per the Square documentation: import uuid from decimal import Decimal from django.utils import … -
How to show following count in template django
I was able to get count for follower/following users, but when user A follow user B, user B accept user A follow request(they are in friends list). After accept request, I want to display count (1) for user A Follower List and user B following list... So it looks like this: user A follower (1) following (1).... For user B follower (1) following (1). Just as the attached image on my question..... class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) friends = models.ManyToManyField('Profile', related_name="my_friends", blank=True) class FriendRequest(models.Model): from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') def ProfileView(request, username): user = request.user friends_received = FriendRequest.objects.filter(to_user=user) # Option 2: Get users that have sent friend requests to the current user friends_sent = FriendRequest.objects.filter(from_user=user) <p><b>{{ friends_sent|length|humanize_number }}</b> Following</p> <p><b>{{ friends_received|length|humanize_number }}</b> Followers</p> -
How can I split the two forms so that only one of the two forms in the template is processed?
Have a nice day! I am trying to place two independent forms on one template. I have them placed but there is a problem that both forms are being checked. Validation of both forms is being checked. Although I only have one button clicked in the first form. How can I split these two forms so that they are independent? I need the form to be checked separately. Separately - the first and second forms. When I fill out one form - I get an error because both forms are being checked. How can I separate the forms - separate the forms during checking. How can I split the two forms so that only one of the two forms in the template is processed? enter image description here views.py def book(request, pk): context = {} Category_pk_for_form_maim.objects.all().delete() filter_qs_category = Category_pk_for_form_category.objects.filter(name_object=pk) filter_qs_category = filter_qs_category.values("category_name") for item in filter_qs_category: entry = item new_entry = Category_pk_for_form_maim(categoty_name=entry) new_entry.save() form_category_1 = Category_pk_for_form_category_Form(request.POST or None) form_2 = Form_GPR(request.POST or None) if request.method == 'POST': if "form_category_1" in request.POST: if form_category_1.is_valid(): model_instance = form_category_1.save(commit=False) name_object = pk category_name = model_instance.category_name new_entry = Category_pk_for_form_category(name_object=name_object, category_name=category_name) new_entry.save() return redirect("book-detail", pk) if "form_2" in request.POST: if form_2.is_valid(): model_instance = form_2.save(commit=False) name_object … -
how to apply the two dropdown selectors in django
form.py: from django import forms from .models import Invoice, InvoiceItem Form for the Invoice model class InvoiceForm(forms.ModelForm): class Meta: model = Invoice fields = ['customer'] labels = { 'customer': 'Select Customer', # 'total_amount': 'Total Amount', } this above core is create a field to choose the customer at the time of bill creation but also i want to add the new field for the product adding in that product field i want to select the product which are present in the product list but whenever i am trying to add one more field in this form for the implementation of this functionality its showing me error please any one can help me to solve this and tell me what is the issue whay am i getting this error?? i am expection to add the input dropdown in the invoice app for the invoice creation -
How do I log filtered GET requests on a Django REST Framework ModelViewSet using @action?
I have a ModelViewSet for EventReportLink and need to log every time someone queries with ?event_report__id=<id>. I’ve tried adding a custom @action(detail=False, methods=['get']), but I’m not sure if I’m implementing it correctly or if there’s a better way. I added: @action(detail=False, methods=['get'], url_path='log-test') def log_test(self, request): event_report_id = request.query_params.get('event_report__id') logger.info(f"ID: {event_report_id}") queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Expecting logs and correct filtering results. I’m receiving filtered results but not sure if this is best practice. What would be a more idiomatic approach? P.S. I also consulted this related question, which discusses how to add behavior before/after the default create logic using super().create(request). However, I wasn’t entirely sure if it applies to my case with query param filtering and logging via @action, so I’m still exploring best practices. -
How to remove hardcoded library version info from minified JS files in Django production?
'm using Django to serve static files in production, and I've noticed that many of the third-party JS libraries (like jQuery, Bootstrap, JSZip, and Moment.js) include hardcoded version numbers inside the minified files. For example: /*! jQuery v3.3.1 */ "version": "3.7.1" [ These version details are accessible to anyone via the browser's DevTools, and I’m concerned this could expose the application to targeted attacks if any of the libraries are outdated. Questions: What is the best way to strip or hide these version numbers from minified JS/CSS in a Django production environment? Should I re-minify third-party libraries myself before using them in Django? Are there best practices or tools recommended for this kind of hardening? Thanks! -
How to integrate ZKTeco ZK4500 fingerprint scanner with a Django + React web application?
I'm working on a web application using Django (backend) and React (frontend), and I want to integrate the ZKTeco ZK4500 fingerprint scanner into my system for user authentication. 🔍 My Setup: Device: ZKTeco ZK4500 (USB fingerprint scanner) Backend: Django (Python) Frontend: React (JavaScript) OS: Windows 10 📌 What I want to achieve: Capture a fingerprint using the ZK4500 from the client machine Send the fingerprint data to the Django backend Use this data to register or authenticate a user 🧩 The problem: Since this is a web-based application, I understand that I cannot directly access USB devices like the ZK4500 via browser (React). I’m confused about: What SDK/library should I use (ZKFinger SDK, BioTime SDK, etc.)? How can I create a middleware (Python/C#/Electron) that communicates with the ZK4500 and sends data to Django? Is there any existing solution or recommended architecture for this? 🧪 What I’ve tried: I’ve searched for ZKTeco SDKs and found references to zkemkeeper and ZKFinger SDK for Windows, but most examples are in C# and are designed for desktop applications. I have not found a clear solution for integration with a web-based stack (Django + React). ❓ My questions: What is the best approach to use … -
Filter some data in one column in table
In a Django project, I want to display values from a table in the database, provided that a filter is applied to some data in one of the columns. For example, the gender column. I want to display only female data with the rest of the columns in the table. -
How to handle constraint errors like unique or not null from DB in Django
I have a write operation which adds a record in rider model. The rider_code is unique in this. Now 1 way is to first check if any record with that rider_code exists then return error else create rider. But it requires 2 db calls when the db can return constraint error on create which would be a single call. But how to catch these constraint errors correctly in Django. This is 1 of the solutions I got but it does not seem right: def create_rider(request): serializer = RiderSerializer(data=request.data, context={"request": request}) if serializer.is_valid(): try: rider = serializer.save() return True, rider except IntegrityError as e: error_msg = str(e) if "ds_riders.ds_riders_rider_code_d4b087a9_uniq" in error_msg: return False, {"details": "Rider Code already exists."} if "application_users.username" in error_msg: return False, {"details": "Username already exists."} return False, {"details": error_msg} return False, serializer.errors` -
Django application deployement with Docker
I am trying to deploy my django app with docker. But when it come to excute my script to be sure that the databse (postgres) is ready, I allways get this error : chmod: /app/scripts/wait-for-it.sh: Permission denied and then the container stop running. This is my dockerfile : # Stage 1: Base build stage FROM python:3.13-slim AS builder # Create the app directory RUN mkdir /api # Set the working directory WORKDIR /api # Set environment variables to optimize Python ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ libpcre3-dev \ libssl-dev \ python3-dev \ libpango1.0-dev \ libcairo2-dev \ libpq-dev \ bash \ fontconfig \ fonts-dejavu-core \ fonts-droid-fallback \ fonts-freefont-ttf \ fonts-liberation \ && rm -rf /var/lib/apt/lists/* # Install dependencies first for caching benefit RUN pip install --upgrade pip RUN mkdir /requirements COPY ./requirements/. ./requirements/. RUN set -e; \ pip3 install --upgrade pip && \ pip3 install uwsgi && \ pip3 install --default-timeout=100 --no-cache-dir -r ./requirements/stage.txt # Stage 2: Production stage FROM python:3.13-slim RUN useradd -m -r -g www-data app_user && \ mkdir /api && \ chown -R app_user /api # Copy the Python dependencies from the builder stage COPY --from=builder /usr/local/lib/python3.13/site-packages/ /usr/local/lib/python3.13/site-packages/ COPY … -
Celery is not running despite correct configuration - using Django, Celery 5+, and Python 3.12+
Despite what appears to be a correct initial configuration, Celery tasks are not running. The logging system does not show any errors. This is a new setup of Celery version 5+ running on Python 3.12+. Full server-side configuration has been added. All required packages and dependencies have been installed, and the application itself does not raise any errors. What could be the reason the test Celery task is not executing every minute as scheduled, according to the interval specified in settings.py? tasks.py from celery import shared_task from datetime import datetime from .models import CeleLog @shared_task def get_all_weather_data(): now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') CeleLog.objects.create(content=f"Current time: {now}") print(f"Logged time: {now}") settings.py CELERY_BROKER_URL = 'amqp://localhost' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'log-every-minute': { 'task': 'company_dashboard.tasks.get_all_weather_data', # <- ścieżka do funkcji 'schedule': crontab(minute='*/1'), }, } celery.py - project import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_rama.settings') app = Celery('app_rama') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) init.py - project from .celery import app as celery_app app-celery-worker.conf [program:app-celery-worker] command=/home/app/bin/celery -A app_rama worker -l INFO directory=/home/app/app user=app numprocs=1 stdout_logfile=/home/app/logs/app-rama-worker.log stderr_logfile=/home/app/logs/app-rama-worker.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 killasgroup=true priority=998 app-celery-beat.conf [program:app-celery-beat] command=/home/app/bin/celery -A app_rama beat -l INFO directory=/home/app/app user=app numprocs=1 stdout_logfile=/home/app/logs/app-rama-worker.log stderr_logfile=/home/app/logs/app-rama-worker.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 killasgroup=true priority=998 And … -
How to make DRF use url path as empty and base path?
I am trying to omit the URL path for an action in a ViewSet like @action(detail=False, methods=['patch'], url_path='') def update_current_user(self, request): But when I give url_path as an empty string, DRF defaults to the function name and looks for the route at /api/current-user/update_current_user. I want it to look at /api/current-user. How to drop the whole path for the function and use the base path? -
ImportError: Module "django_comments_xtd" does not define a "XtdComment" attribute/class
When I installed django-comments-xtd according the documention I got this error: ImportError: Module "django_comments_xtd" does not define a "XtdComment" attribute/class Configs in settings.py are: INSTALLED_APPS += [ 'django_comments_xtd', 'django_comments', 'django.contrib.sites', ] SITE_ID = 1 COMMENTS_APP = "django_comments_xtd" COMMENTS_XTD_MODEL = 'django_comments_xtd.XtdComment' COMMENTS_XTD_MAX_THREAD_LEVEL = 3 COMMENTS_XTD_CONFIRM_EMAIL = False COMMENTS_XTD_ALLOW_ANONYMOUS = True COMMENTS_XTD_ALLOW_PUBLICATION_MODERATION = True -
Django forloop in template
Forloop is overriding the other, how do I use two different forloop in one template without interrupting each other. The 'include template" do not display its contents if 'for users in all_users' is the parents. How do I make 'for users in all_users' not to override 'for post in posts'. What I tired: I tried using same context key but still not working, also tried using 'with' inside the include.html still no problem solved. def ForYouView(request): #All account users all_users = Profile.objects.exclude( Q(user=request.user)| Q(friends__user=request.user)).order_by("?") posts = Post.objects.all().order_by("?") context = { 'posts': posts, 'all_users': all_users, } #Home template {% for users in all_users %} <div>{{ users.user }}</div> {% include 'index_hover_card.html' %} <div>{{ users.user.username }}</div> {% endfor %} #Include template {% for post in posts %} <div>{{ post.poster_profile.profile.user }}</div> {% endfor %} -
ERROR: Failed to build installable wheels for some pyproject.toml based projects (mysqlclient)
Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [91 lines of output] C:\Users\Acer\AppData\Local\Temp\pip-build-env-qm2za2yg\overlay\Lib\site-packages\setuptools\config_apply_pyprojecttoml.py:82: SetuptoolsDeprecationWarning: project.license as a TOML table is deprecated !! ******************************************************************************** Please use a simple string containing a SPDX expression for `project.license`. You can also use `project.license-files`. (Both options available on setuptools>=77.0.0). By 2026-Feb-18, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details. ******************************************************************************** !! corresp(dist, value, root_dir) C:\Users\Acer\AppData\Local\Temp\pip-build-env-qm2za2yg\overlay\Lib\site-packages\setuptools\config\_apply_pyprojecttoml.py:61: SetuptoolsDeprecationWarning: License classifiers are deprecated. !! ******************************************************************************** Please consider removing the following classifiers in favor of a SPDX license expression: License :: OSI Approved :: GNU General Public License (GPL) See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details. ******************************************************************************** !! dist._finalize_license_expression() C:\Users\Acer\AppData\Local\Temp\pip-build-env-qm2za2yg\overlay\Lib\site-packages\setuptools\dist.py:759: SetuptoolsDeprecationWarning: License classifiers are deprecated. !! ******************************************************************************** Please consider removing the following classifiers in favor of a SPDX license expression: License :: OSI Approved :: GNU General Public License (GPL) See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details. ******************************************************************************** !! self._finalize_license_expression() # Options for building extension module: library_dirs: ['C:/mariadb-connector\\lib\\mariadb', 'C:/mariadb-connector\\lib'] libraries: ['kernel32', 'advapi32', 'wsock32', 'shlwapi', 'Ws2_32', 'crypt32', 'secur32', 'bcrypt', 'mariadbclient'] extra_link_args: ['/MANIFEST'] include_dirs: ['C:/mariadb-connector\\include\\mariadb', 'C:/mariadb-connector\\include'] extra_objects: [] define_macros: [('version_info', (2, 2, 4, 'final', 0)), ('__version__', '2.2.4')] …