Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch: Reverse for 'chat_chatroom_changelist' not found. 'chat_chatroom_changelist' is not a valid view function or pattern name
Im triyng to register model in django admin, but i get error backend-1 | Couldnt reverse admin:chat_chatroom_changelist. Im using jazzmin for customize admin panel, and i setting up it for model JAZZMIN_SETTINGS { 'name':_('Chat'), 'model': 'chat.ChatRoom', 'url': 'admin:chat_chatroom_changelist', 'permissions': ['auth.view_user'], }, Model has been register in admin.py @admin.register(ChatRoom) class ChatRoomAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('first_user', 'second_user')}), (_('Important dates'), {'fields': ('created_at', 'updated_at')}), ) list_display = ('id', 'first_user', 'second_user', 'created_at', 'updated_at') readonly_fields = ('created_at', 'updated_at') list_display_links = ('id', 'first_user', 'second_user') show_full_result_count = False def get_queryset(self, request): return super().get_queryset(request).select_related('first_user', 'second_user').order_by('-created_at') def get_history_queryset(self, request, history_manager, pk_name: str, object_id): qs = super().get_history_queryset(request, history_manager, pk_name, object_id) return qs.prefetch_related('history_user') model class ChatRoom(TimestampMixin, models.Model): first_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='first_user') second_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='second_user') def __str__(self): return ' / '.join([str(self.first_user), str(self.second_user)]) class Meta: db_table = 'chatrooms' app_label = 'chat' Project structure _|apps __|chat ___|admin ____|admin.py ___|models ____|chat.py ___|url.py ___|... __|... __|asgi.py __|wsgi.py _|settings __|main.py __|base.py __|jazzmin.py _|... -
Django Project on Azure, 502 error after deployment
I'm deploying a Django app on Azure Web App using Gunicorn and keep getting a 502 Bad Gateway error. Despite binding to the correct port, setting up environment variables for Key Vault, and enabling SCM_DO_BUILD_DURING_DEPLOYMENT for Oryx builds, the site never fully starts. I need to figure out why Gunicorn won't serve the app properly, even though the deployment logs seem fine. I set SCM_DO_BUILD_DURING_DEPLOYMENT=true, placed my requirements.txt in the project root so Oryx could install dependencies, and updated my startup command to gunicorn --bind=0.0.0.0:$PORT. I also configured environment variables for Key Vault, and tested collecting static files locally vs. on Azure. I expected the Azure Web App to run Gunicorn without errors. Instead, I keep getting a 502 Bad Gateway, and my logs show no direct failure message—just that the service never properly responds. -
When and where i use create_user from CreateUserManager()?
For several days now, I've been wondering why I should create my own user manager in Django, since in the end, when inheriting a built-in form, I don't refer to my created manager anyway. class CustomUserManager(BaseUserManager): def create_user(self, email, birth_date, password=None, **extra_fields): if not email: raise ValueError("You didn't entered a valid email address!") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_stuff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) I have something like this and in the end when it creates a user it doesn't go through that create_user anyway. So my two questions: Why create something for a custom user if I don't end up using it anyway because the form inherits from UserCreationForm. So, for example, form.save() does not use my manager. At what point should this create_user be executed? -
asynchronously database routing in djago and celery
I am implementing subdomain-based database routing, and it is working fine. However, when a task is executed asynchronously, the database that has been dynamically routed gets overwritten by the default one. How to handle that in Django? # middleware.py from django.db import connections from django.conf import settings from django.http import HttpResponse class SubdomainDatabaseMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Get subdomain from the request subdomain = request.META.get('HTTP_HOST', '').split('.')[0] subdomain = 'tenant' # Set the database connection based on subdomain if subdomain: request.subdomain = subdomain self.set_database(subdomain) else: request.subdomain = None response = self.get_response(request) return response def set_database(self, subdomain): # Dynamically set database for the subdomain database_alias = f'{subdomain}' if database_alias in settings.DATABASES: connections['default'] = connections[database_alias] else: # Default behavior if no database configured for subdomain pass -
Django "No installed app with label 'logs'" Error Even After Correcting Project Structure
I'm encountering a persistent "No installed app with label 'logs'" error in my Django project, even after seemingly correcting the project structure and INSTALLED_APPS. I've tried all the common solutions, but the issue remains. Python Version: 3.13.2 Django Version: 5.1.6 os: Windows 11 Project Structure router_log_project/ manage.py router_log_project/ (Inner project directory) __init__.py settings.py urls.py wsgi.py logs/ __init__.py models.py views.py migrations/ __init__.py env/ db.sqlite3 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'logs', ] Steps already taken Double-checked INSTALLED_APPS: I've meticulously verified the spelling of 'logs' in INSTALLED_APPS. Verified __init__.py files: I've confirmed that __init__.py files exist in both the inner router_log_project directory and the logs app directory. Restarted the development server: I've restarted the server multiple times after making changes. Deactivated/reactivated the virtual environment: I've tried creating a fresh virtual environment. -
Where the source code files are stored by azure in case of a web app on linux for a python website?
I've created a web app on azure for a python web app. I've successfully deployed it using zip and an azure cli command. It worked and my website works now. But what's really confusing to me is that I don't see my website files via filezilla. I mean it should contain all those scripts and the database file. I'm using sqlite db there. So if I just want to upload some image manually or download a database for a backup or local work with up to date PROD database, how do I do that? The only thing that I've found there is a output.tar.gz file, which contains output.tar file, which contains all of my website files and the database file as well. But would azure server hold all the files that a website is currently using in an archive? It would slow down an app, so I don't believe that those files are up to date with actual working PROD website instance. So how can I download the database file from PROD to my local? -
django reconnect to DB when connection is lost
I have django project, Mysql DB is on a separate host, connected by TCP. I have this script: #!/usr/bin/env python from asyncio import sleep, run from django import setup as django_setup django_setup() from django.db import connections from django.contrib.auth.models import User from django.db import OperationalError, close_old_connections async def test(): while True: try: objs=User.objects.all() print(await objs.acount()) except KeyboardInterrupt: break except OperationalError as e: # Need to reconnect print(f'main(): OperationalError: {e}') #raise # (1053, 'Server shutdown in progress') # (2013, 'Lost connection to MySQL server during query') # (2006, 'Server has gone away') code=e.args[0] if code in {1053, 2006, 2013, 2026}: # Only when it's restarting, and once #await sync_to_async(conn.connect)() close_old_connections() print('After reconnect') #reconnect() else: #breakpoint() pass except Exception as e: print(f'in _round() {type(e)}') else: pass #breakpoint() print('Sleeping') await sleep(5) try: run(test()) except KeyboardInterrupt: raise except: print('In run(main())') breakpoint() pass Then I use tcpkill to interrupt the connection: tcpkill 'dst port 3306' How do I instruct django to reconnect? I doesn't do it automatically, close_old_connection doesn't work, the output is then like this: 3 Sleeping 3 Sleeping main(): OperationalError: (2013, 'Lost connection to MySQL server during query') After reconnect Sleeping main(): OperationalError: (2013, 'Lost connection to MySQL server during query') After reconnect Sleeping … -
When deployed to the server (in production), the Gemini API server's streaming responses are not received
It works fine locally. In the production environment, non-streaming responses work well. When I send a Gemini API request directly from the AWS server using curl, the streaming works perfectly. However, when I run the backend server with Gunicorn, the Gemini API streaming does not work. I tried using both gevent and eventlet for the worker class, but neither worked. It doesn't seem to be an issue with the nginx configuration, since streaming responses to the client are sent correctly. The problem only occurs when the server calls the outer API. Actually, everything worked fine when I first set up the server. But ever since I set up the CI/CD pipeline, (I just tried to use github actions and install requirements remote) external API streaming doesn't work. Since it's a Django codebase, even deleting the virtual environment and reinstalling, or installing using the requirements.txt from before the CI/CD build (when it was working fine), doesn't resolve the issue. What should I do? What I got from gunicorn logs [2025-02-14 14:29:50 +0000] [5235] [CRITICAL] WORKER TIMEOUT (pid:5283) Feb 14 14:29:50 ip-172-31-13-205 gunicorn[5283]: response: Feb 14 14:29:50 ip-172-31-13-205 gunicorn[5283]: GenerateContentResponse( Feb 14 14:29:50 ip-172-31-13-205 gunicorn[5283]: done=False, Feb 14 14:29:50 ip-172-31-13-205 gunicorn[5283]: iterator=<_StreamingResponseIterator>, … -
Django-admin makemessages does not detect ngettext strings from .html files (but it detects gettext strings)
Django-admin makemessages does not detect ngettext strings from .html files (write in jinja2), but it is able to detect them in .py files. However, the same command normally detects gettext strings everywhere (including in .html files). I tried django-admin makemessages -l en --ignore="*/site-packages/*" --ignore="*/django/*" and my code in .html is {{ ngettext( '%(num)d lesson', '%(num)d lessons', 3) | format(num=3) }} -
BrowsableAPIRenderer doens't have a file upload field
I'm trying to have an image upload field, so I could upload multiple images per post. But it seems like it doesn't have a file upload field, let alone that would allow and save multiple files. views.py class PostsViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAuthenticated, IsOwnerOrReadOnly|IsAdminUser] filter_backends = (filters.DjangoFilterBackend,) filterset_class = PostFilter parser_classes = [JSONParser, MultiPartParser, FileUploadParser] renderer_classes = [JSONRenderer, BrowsableAPIRenderer] serializers.py class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('image',) class PostSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) comments = CommentSerializer(many=True, read_only=True, source='comment_set') likes_count = serializers.SerializerMethodField() images = PostImageSerializer(source='postimage_set', many=True, read_only=True) class Meta: model = Post fields = "__all__" def create(self, validated_data): validated_data["author"] = self.context["request"].user images_data = self.context.get('view').request.FILES print(validated_data) post = Post.objects.create(text=validated_data.get('text'), author=validated_data.get('author')) for image_data in images_data.values(): PostImage.objects.create(post=post, image=image_data) return post models.py class Post(models.Model): id = models.AutoField(primary_key=True) text = models.TextField(max_length=165) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author} posts "{self.text}"' class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True) and it looks like this Where's error? -
How do I save a Historical field on a non-historical model in Django Simple History?
I have something like a ContractTemplate shared for all clients which is 'versioned' through django-simple-history. I have a ClientContract that I want to attach a HistoricalContractTemplate as a field, so I can tell what the ContractTemplate looked at the time the ClientContract was created. class ContractTemplate(models.Model): text = models.TextField() # Create table 'HistoricalContractTemplate' which stores all changes history = HistoricalRecords() class ClientContract(models.Model): client_text = models.TextField() contract_template_version = ???? # <------ And after I set up the model right, how do I use it? def update_client_contract(contract_template_that_will_get_stale): # ... update other client contract fields newest_history_record_of_this_contract_template = ??? # <--- client_contract.contract_template_version= newest_history_record_of_this_contract_template -
Django - multiple models in one view
I have scoured the StackOverflow pages and none of the solutions to this problem are working for me. I have two models in the same app and am trying to display data from both models in the same template using class based DetailView. This is my code, but the only thing that displays is the data from the Project model. models.py from django.db import models class Project(models.Model): project_name = models.CharField(max_length=100) project_location = models.CharField(max_length=100) def __str__(self): return self.project_name class Well(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) well_name = models.CharField(max_length=100) def __str__(self): return self.well_name views.py class ProjectDetailView(DetailView): model = Project template_name = 'project/project_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['projects'] = Project.objects.all() context['wells'] = Well.objects.all() return context html {{ project.project_name}} {{ well.well_name}} What am I missing? The Django docs for TemplateView only show how to display data from one model, not two. -
How Can I Get Django Global Notifications Via Channels To Work?
I have spent the last month or so on and off trying to get the django channels notification to work. I can't get notifications to work but the chat works as expected. Here is my code... Consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.is_group_chat = 'group_name' in self.scope['url_route']['kwargs'] if self.is_group_chat: group_name = self.scope['url_route']['kwargs'].get('group_name') self.group_name = group_name.replace('_', ' ') # Replace underscores with spaces try: self.group_chat = await database_sync_to_async(GroupChat.objects.get)(name=self.group_name) except GroupChat.DoesNotExist: await self.close() return self.chat_group = f'group_{self.group_name.replace(" ", "_")}' else: self.recipient_username = self.scope['url_route']['kwargs'].get('recipient_username') self.sender = self.scope['user'] self.conversation_group = self.get_conversation_group_name( self.sender.username, self.recipient_username ) # Convert recipient_username to a User object and assign it to self.recipient try: self.recipient = await database_sync_to_async(get_user_model().objects.get)(username=self.recipient_username) except get_user_model().DoesNotExist: await self.close() return # Join the group if self.is_group_chat: await self.channel_layer.group_add( self.chat_group, self.channel_name ) else: await self.channel_layer.group_add( self.conversation_group, self.channel_name ) await self.accept() def get_conversation_group_name(self, user1, user2): return f'chat_{sorted([user1, user2])[0]}_{sorted([user1, user2])[1]}' async def disconnect(self, close_code): if self.is_group_chat: await self.channel_layer.group_discard( self.chat_group, self.channel_name ) else: await self.channel_layer.group_discard( self.conversation_group, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) timestamp = timezone.now().isoformat() sender = self.scope['user'] sender_full_name = await self.get_user_full_name(sender) # Fetch full name message = text_data_json.get('message', '') attachment = text_data_json.get('attachment', None) message_type = text_data_json.get('type') # Ensure sender full name is calculated sender_full_name = await self.get_user_full_name(sender) if … -
exclude specific urls from nginx redirect
I'm trying to exclude two URLs from nginx redirect (http to https). Traffic from Nginx is sent to guincorn and the URLs are generated dynamically by the Django view. My current base nginx configuration for the site is below. All non http requests are sent to https using this. server { listen 80; listen [::]:80 default_server; server_name mydomain.org; return 301 https://$server_name$request_uri; } server { listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_certificate ....; ssl_certificate_key ....; root /app/ioc; server_name mydomain.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /path/static/; } location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $remote_addr; proxy_redirect off; } } Now, I'm trying to exclude both this/endpoint1.txt and this/endpoint2.txt from the redirects. endpoint1.txt and endpoint1.txt are dynamically generated by the django view so they are not actual text files on the server. Trying to do something like this results in 404 error location /this/endpoint1.txt { root /path/app; add_header Content-Type text/plain; } Also, when I do something like this: location /this/endpoint1.txt { proxy_pass http://127.0.0.1:80; } I get 504 Gateway Time-out error. I'm binding gunicorn like this "0.0.0.0:8000" -
Best way to implement date with optional day/month?
There are several ways to do this, each with their own advantages and disadvantages. Boolean fields for day/month: Advantages: cheap ordering, easy formatting, easy validation Disadvantages: have to provide a default month/day, ordering may not behave as expected depending on needs date = models.DateField() date_has_month = models.BooleanField() date_has_day = models.BooleanField() Separate IntegerFields Advantages: relatively cheap ordering, flexible ordering with not_null option etc Disadvantages: complicates date validation, must order on several fields, must compose date from several fields date_year = models.IntegerField() date_month = models.IntegerField() date_day = models.IntegerField() CharField Advantages: no need for extra fields, 1:1 with user input (depending on validation) Disadvantages: relatively expensive ordering, ordering is inflexible, validation may be complicated date = models.CharField() My question is: are there more (dis)advantages not listed? Are there other ways to achieve this that I haven't thought of? -
backward lookup is not working in django 5.x
We are migrating our django app from django==3.2.25 to django==5.1.6. OneToOneField, ManyToManyField are giving errors on revers lookup. I have models as below. from django.db import models class Switch(models.Model): fqdn = models.CharField(max_length=45, unique=True) class Meta: managed = False db_table = 'Switch' app_label = 'myapp_models' class ConfigState(models.Model): switch = models.OneToOneField(Switch, models.CASCADE, db_column='switch', primary_key=True, related_name='config_state') class Meta: managed = False db_table = 'ConfigState' app_label = 'myapp_models' class EdgeSwitch(models.Model): switch = models.OneToOneField(Switch, models.CASCADE, db_column='switch', primary_key=True, related_name='edge_switch') class Meta: managed = False db_table = 'EdgeSwitch' app_label = 'myapp_models' When I try to get backward lookup query in DJango==3.X it works. >>> print(EdgeSwitch.objects.filter(switch__config_state=1).query) SELECT `EdgeSwitch`.`switch`, `EdgeSwitch`.`cluster`, `EdgeSwitch`.`sequence`, `EdgeSwitch`.`position`, `EdgeSwitch`.`role`, `EdgeSwitch`.`span`, `EdgeSwitch`.`loopback_v4`, `EdgeSwitch`.`loopback_v6` FROM `EdgeSwitch` INNER JOIN `Switch` ON (`EdgeSwitch`.`switch` = `Switch`.`id`) INNER JOIN `ConfigState` ON (`Switch`.`id` = `ConfigState`.`switch`) WHERE `ConfigState`.`switch` = 1 Same code gives error in DJango==5.X >>> print(EdgeSwitch.objects.filter(switch__config_state=1).query) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/query.py", line 1476, in filter return self._filter_or_exclude(False, args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/query.py", line 1494, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/query.py", line 1501, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/sql/query.py", line 1609, in add_q clause, _ = self._add_q(q_object, self.used_aliases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/sql/query.py", line … -
Django DRF showing weired auth methode respective to URL
I'm facing a strange issue with Django REST Framework (DRF). # views.py class CheckoutView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): return Response({'total_price': 7879}) #url.py urlpatterns = [ path("cart/checkout/<int:new>", checkoutView.as_view() , name="checkout"), # url 1 path("cart/checkout/", checkoutView.as_view() , name="checkout"), # url 2 ] issue : if i hit with url 1 it gives response 200 if i hit url 2 it gives response 401 { "detail": "Authentication credentials were not provided." } note that : 'permission_classes = [AllowAny]' is there in the view also i dont have defined default permission class in settings.py -
Django can't load static files, even with correct settings
Today i faced a problem with static files. I was adding JavaScript and CSS to my project, but the app could not load it. It did find the files, but could not load them, because the app shows 404 code (see picture). I made sure that i have these lines in my settings.py: STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static' Then i made sure i ran collectstatic command and linked them in html template. <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/script.js' %}"></script> Anyway, i got 404 in console section of browser Google Chrome Console This is the second time i'm facing this problem. On my previous little project as wel, I encountered the same problem. I tried to find solution to this problem from every corner of internet: this site, django forum and other forums. But i could not find any solution. I have a thought that this problem may be with my laptop or OS maybe. My OS is Linux Ubuntu 22.04 LTS. If there is someone that encountered same problem or has any idea how to solve this problem, I would be glad. -
How to persist default class configurations in the database?
Let's say I've a ToDo model and Point model with foreign key relation in database. class Todo(ManuallyTimestampedModel): title = models.CharField(max_length=255) description = models.TextField() class Point(Model): title = models.CharField(max_length=255) description = models.TextField() todo = models.ForeignKey( Todo, on_delete=models.CASCADE, related_name="points", help_text=_("ToDo to which point belongs."), ) I also have a function for creating a few todos and points assigned to then based on chosen option: class PlanType(enum.Enum): RUNNING = "Running" SWIMMING = "Swimming" def plan(option: PlanType) -> None: todos = [] if option == PlanType.RUNNING: options = ... elif option == PlanType.SWIMMING: options = ... return todos What is a good approach to load default todos and points based on chosen option? I plan to store them in database with possibility to edit via admin UI. -
Can't see any results from Celery Beat in Django Project
I want to run scheduled tasks in my django backend with celery and celery beat. I have a Dockerfile config for both celery container beside the normal django container. I cant see any results from the execution. Does anyone have an idea? both with this config, just one with "worker" and one with "beat" in last line: # Use an official Python runtime as a parent image FROM python:3.11-slim ENV PYTHONUNBUFFERED 1 ENV APP_HOME=/usr/src/app # Set the working directory in the container WORKDIR /usr/src/app # Install Pip Packages RUN pip install --upgrade pip COPY server/requirements.txt $APP_HOME RUN pip install --no-cache-dir -r requirements.txt # Copy the rest of the application code into the container COPY server $APP_HOME # Define environment variable ENV DJANGO_SETTINGS_MODULE=musterteile_server.settings # Create a non-root user and change ownership of APP_HOME RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser && \ chown -R appuser:appgroup $APP_HOME # Switch to the non-root user USER appuser # Run Celery worker CMD ["celery", "-A", "musterteile_server.celery", "worker", "-E", "--loglevel=info"] musterteile_server/settings.py has the config for celery with a beat schedule for a test task. CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL", "redis://localhost:6379/0") CELERY_RESULT_BACKEND = os.environ.get( "CELERY_RESULT_BACKEND", "redis://localhost:6379/0" ) CELERY_CONFIG_MODULE = os.environ.get( "CELERY_CONFIG_MODULE", "musterteile_server.celery" ) CELERY_TIMEZONE = os.getenv("TIME_ZONE", … -
setting acks_late=True doesnt re-execute the task if worker process is killed
i want to reproduce this behaviour highlighted in celery doc If the worker won’t shutdown after considerate time, for being stuck in an infinite-loop or similar, you can use the KILL signal to force terminate the worker: but be aware that currently executing tasks will be lost (i.e., unless the tasks have the acks_late option set). this is my task: @shared_task( name='CHECK_ACK', acks_late=True, ) def check_ack(): print('task picked') time.sleep(60) print('task completed after 60r seconds') here are steps i am following: 1.start celery: celery -A master worker --concurrency=2 2.run the task from django shell: check_ack.delay() 3. while task is running execute :pkill -9 -f 'master worker' 4. now restart celery again : celery -A master worker --concurrency=2 But i don't see the task getting re-picked by workers. What am i missing? -
Get data from views to a Javascipt file
In django, I'm trying to make a webapp where the the graph is defined in javascript and I want the data to come from firebase (the only way I know to get that data is in the views) how do I pass the data to it since what I only know is to pass that data to html I've tried using json response, but I dont know how to route the data to the static files where the javascript is located -
DJANGO + FIREBASE deployment with ssl certificate
I am currently deploying a django project that uses firebase_admin. at first when it was just deployed i can access it smoothly when it was just an ip provided by amazon aws. but when i used the bought ssl certificate and domain, after setting up everything, it now returns internal error 500 when i am trying to use from firebase_admin import messaging. but when i comment out everything about firebase, the website works. when i looked in the error logs it says no module _ssl i tried everything(i think). tried rebuilding python remaking virtualenv installing libssl almost everything that i saw on the internet while searching but nothing has worked yet in my django views.py when I do this import firebase_admin from firebase_admin import credentials it's fine like the site will work but when i do it like this import firebase_admin from firebase_admin import credentials, messaging i get this error in the apache2 error log [Thu Feb 13 08:52:34.813237 2025] [wsgi:error] [pid 1687181:tid 1687236] [remote xxx.xxx.x.xx:xxxxx] import ssl [Thu Feb 13 08:52:34.813243 2025] [wsgi:error] [pid 1687181:tid 1687236] [remote xxx.xxx.x.xx:xxxxx] File "/opt/bitnami/python/lib/python3.11/ssl.py", line 100, in <module> [Thu Feb 13 08:52:34.813246 2025] [wsgi:error] [pid 1687181:tid 1687236] [remote xxx.xxx.x.xx:xxxxx] import _ssl # if … -
A problem occurs when adding a new foreign key field to a model
So, I added a foreign key field to my model, ran "makemigrations" and "migrate" without problems, but when I check my database via DB browser, I cannot find that field! This is my model class Listing (models.Model): CATEGORY_CHOICES = [ ("chemistry", "Chemistry"), ("physics", "Physics"), ("math", "Math"), ("litreture", "Litreture"), ("history", "History"), ("language", "Language"), ("sports", "Sports") ] title = models.CharField(max_length=80) brief = models.CharField(max_length=128) description = models.TextField() intial_price = models.IntegerField() category = models.CharField(max_length=24, choices=CATEGORY_CHOICES) # The problem is within the line below creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='listings') # I cannot find this field in my database file when browsing it via DB browser def __str__(self): return self.title I tried to ask the AI a lot but all it said was to check the migrations files and make sure the migration process is successful. I am sure that there is no issue with those two. I ran out of ideas, help! -
Best place to initialize a variable from a postgres database table after django project startup
I have a django project where I have some database tables. One of the database tables is designed to store messages and their titles. This helps me to create/alter these messages from my django-admin. Now I want to initialize a variable (as a dictionary) from this table as follows : MY_MSGS = {record.name : {'title':record.title, 'message':record.message} for record in MyTable.objects.all()} This must happen at the server startup for now. MY_MSGS must be accessible to the different view-files. FYI I have multiple view-files that are all imported from views.py