Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ci/CD using GitHub actions and AWS EC2
I am trying to implement cicd using github actions and ec2. I have 2 apps - testing and production in same ec2. I need to run cicd when pull request is closed in staging branch main.yml name: build-and-deploy on: pull_request: types: - closed branches: - main - staging env: TARGET_BRANCH: ${{ github.event.pull_request.base.ref }} jobs: To build the project build: runs-on: ubuntu-latest steps: - name: Checking out code uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.10.12 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r req.txt deploy_staging: runs-on: ubuntu-latest needs: build if: github.event.pull_request.base.ref == 'staging' steps: - name: Debugging Info run: | echo "EC2_PRIVATE_KEY: ${{ secrets.EC2_PRIVATE_KEY }}" echo "EC2_HOST: ${{ secrets.EC2_HOST }}" echo "EC2_USERNAME: ${{ secrets.EC2_USERNAME }}" echo "Current Directory: $(pwd)" - name: Deploy to Staging uses: appleboy/scp-action@master with: host: ${{ secrets.EC2_HOST }} username: ${{ secrets.EC2_USERNAME }} key: ${{ secrets.EC2_PRIVATE_KEY }} source: "./" # Specify the source as the root of the repository target: "/home/ubuntu/plane-project-staging/plane_api/" - name: Run additional commands on Staging run: | /home/ubuntu/plane-project-staging/plane_api/ python manage.py migrate -
Django channels start runworker with same consumer multiple times and automatically init all workers
I am trying to build up a more or less scalable infrastructure with django channels: I have a consumer called sendConsumer which is connected via wss to server A and everytime I send a signal to that consumer from django it forwards it to the server A. Then I have a consumer called receiveConsumer which is connected via wss to server B where I retrive thousends of events per second. However now I want to scale this approach up and have multiple background consumers (so multiple wss connections to server B) and the documentation is unfortunally very quite about this. And yes I really need django channels and not a task queue: In my case django channels is the best approach rather than using celery or similar as I want to be able to send updates to the workers from a django view or a signal to update parameters on the fly. My idea to solve that issue was to create multiple systemd files that have their own environment variables and therefore every worker can start with its own id. In addition with that I modified the apps.py to send an inital message to the worker to basically wake it … -
How to Structure Models and Forms
I'm working on a Django app to track scoring for Golf. I'm currently spinning my wheels on how to structure my models and forms for a scorecard form. I've found forms to be a bit more difficult than I thought they would be. I'm trying to figure out if i'm going about this the right way? i've thought about combining the GolfRound and GolfHole into one model, but it feels kind of wrong to have a field for each hole. I'm leaning towards a nested inlineformset, but i'm not sure if that's the right approach. Here are my models: ***MODELS*** class TeeTime(models.Model): updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) activity = models.ForeignKey(GolfActivity, on_delete=models.CASCADE, related_name='event_teetime') tee_time = models.TimeField(auto_now=False, auto_now_add=False, blank=True) players = models.ManyToManyField(GolfTripMember, blank=True, through='TeeTimePlayers') class GolfRound(models.Model): tee_time = models.ForeignKey(TeeTime, on_delete=models.CASCADE, related_name = 'round') golfer = models.ForeignKey(GolfTripMember, on_delete=models.CASCADE, related_name = 'round_player') gross_score = models.IntegerField(null=True) net_score = models.IntegerField(null=True) par_3 = models.BooleanField(null=True, default=False) complete = models.BooleanField(null=True, default=False) active = models.BooleanField(null=True, default=False) class HoleScore(models.Model): name = models.IntegerField(choices=INDEX, default = INDEX[0][0]) par = models.IntegerField(null=True) HCP_index = models.IntegerField(null=True) netscore = models.IntegerField(null=True, blank=True) grossscore = models.IntegerField(null=True, blank=True) Any thoughts on my model structure, and approaches I should take to implement the form? Here is a typical scorecard for … -
Stripe Checkout Input Not Showing Properly Django
Couldn't find why card details input of stripe is showing like this SS of Problem 1: [Input not showing properly] 2: [Image of how it should be shown] using Django here is my checkout.js // Create a Stripe client. var stripe = Stripe('pk_test_51K4fECSGVkDCNvQ2xw1cHS4RcgdDEsYPDLy5vOJoG8a9whSkP53yscb57okeJQMRyDLawodCrJtjE05W0EgLu58s00Y2zFEz9V'); // Create an instance of Elements. var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. // (Note that this demo uses a wider set of styles than the guide below.) var style = { base: { color: '#32325d', lineHeight: '18px', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; // Create an instance of the card Element. var card = elements.create('card', {style: style}); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element'); // Handle real-time validation errors from the card Element. card.addEventListener('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); // Handle form submission. var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card).then(function(result) { if (result.error) { // Inform the user if there was an error. var errorElement = document.getElementById('card-errors'); … -
Django - Office 365 send message via distribution group
I'm trying to send email in Django using a distribution group as a the DEFAULT_FROM_EMAIL setting. I am using Office 365 to send it. I have wrestled with the package called django-o365mail and python-o365to get it to a functional state. The documentation for that was pathetic enough. I'm not interested in learning miniscule details to send an email message via Office 365 or any other third party platform that believes it has all the answers. It ought to be straightforward, and we have chosen as an industry to make it hard. [Rant over.] Here are my appropriate settings: DEFAULT_FROM_EMAIL = "distribution_list@example.com" EMAIL_BACKEND = 'django_o365mail.EmailBackend' O365_MAIL_CLIENT_ID = env('O365_MAIL_CLIENT_ID') O365_MAIL_CLIENT_SECRET = env('O365_MAIL_CLIENT_SECRET') O365_MAIL_TENANT_ID = env('O365_MAIL_TENANT_ID') O365_ACTUALLY_SEND_IN_DEBUG = True O365_MAIL_MAILBOX_KWARGS = {'resource': 'distribution_list@example.com'} I have tried various ways of achieving my goal, and here are some error messages to guide your thought processes on an incorrect path that you may believe to be the solution to everything. Remember, I just want to send an email to a distribution group from that very group. 404 Client Error: Not Found for url: https://graph.microsoft.com/v1.0/users/distribution_list@example.com/sendMail | Error Message: The requested user 'distribution_list@example.com' is invalid. I received this error when setting DEFAULT_FROM_EMAIL to 'distribution_list@example.com' and the O365_MAIL_MAILBOX_KWARGS as … -
get ViewSet and http_methods from url namespace
I have this snippet to construct API URLs using SimpeRouter(). In the urlpatterns I have declared a namespace called my_api, is there a way to get all the associated ViewSets and their respective http_method properties? from django.urls import include, path from rest_framework import routers from apps.dir.api.views import ( ViewSet1, ViewSet2, ViewSet3, ) router = routers.SimpleRouter(trailing_slash=False) router.register("set1", ViewSet1) router.register("set2", ViewSet2) router.register("set3", ViewSet3) urlpatterns = [ path("api/v1/", include((router.urls, "api_all_sets"), namespace="my_api")), ] -
Security considerations in a nginx and uwsgi serve and django
I am deploing a django app in a server with ubuntu as SO and nginx with uwsgi for the webserver and I want to know the security configuration I should use. I deploy the web page in local with virtualbox and everything works fine. The problem is that I want to deploy it and all the tutorial I followed didnt included security. The only thing I know is to secure the webpage with ssl. I am new to this tool and I tried to read the security documentacion of nginx and uwsgi and I dont understand anything -
How to combine crop image method with different models, with django admin?
I have a django app and I have two models where a user can upload an image: Animal class Animal(models.Model): images = models.ImageField( upload_to="media/photos/animals", blank=True, null=True, verbose_name="Foto") def save( self, force_insert=False, force_update=False, using=None, update_fields=None ): self.slug = slugify(self.name) crop_image(self) super(Category, self).save() And Category: class Category(models.Model): images = models.ImageField( upload_to="media/photos/categories", blank=True, null=True, verbose_name="Foto") def save(self): self.slug = slugify(self.name) crop_image(self) super(Animal, self).save() And I have a crop method for images def crop_image(self, *args, **kwargs): im = Image.open(self.images) if im.mode == "JPEG": pass elif im.mode in ["RGBA", "P"]: im = im.convert("RGB") output = BytesIO() # Resize/modify the image - desired short edge of 200 pixels original_width, original_height = im.size if original_width > original_height: # landscape image aspect_ratio = round(original_width / original_height, 2) desired_height = 200 desired_width = round(desired_height * aspect_ratio) im = im.resize((desired_width, desired_height), Image.LANCZOS) elif original_height > original_width: # portrait image aspect_ratio = round(original_height / original_width, 2) desired_width = 200 desired_height = round(desired_width * aspect_ratio) im = im.resize((desired_width, desired_height), Image.LANCZOS) elif original_height == original_width: # square image desired_width = 200 desired_height = 200 # Resize the image im = im.resize((desired_width, desired_height), Image.LANCZOS) # after modifications, save it to the output im.save(output, format='JPEG', subsampling=0, quality=95) output.seek(0) # change the imagefield value to be … -
Card showing underneath header when page loads on phone (CSS)
I'm designing a website, and want the div named card to load underneath the header when loading the website on mobile devices, but when I lower the card's position on the page, it applies the same repositioning on the desktop version as well. This is using the Django framework as well if that would be helpful. How the page looks on desktop: How the page looks on mobile view: This is the code I'm using: body { padding-top: 10px; } .header { font-family: Dubai; width: 100%; top: 0; left: 0; position: fixed; padding-left: 3.5%; display: flex; background: linear-gradient(to right, #000000 280px, #808080 280px); z-index: 2; } .header ul { list-style-type: none; margin-right: 7%; overflow: hidden; margin-left: 5%; } .header li { float: right; font-size: 100%; } .header li a { color: white; display: block; padding: 8px 16px; text-decoration: none; } .header li a:hover { background-color: #575757; } .header img { width: 140px; height: 60px; margin-top: 7px; } #banner { background-image: url('../../static/mainbanner.jpg'); height: 500px; background-position: center; background-repeat: no-repeat; background-size: cover; margin-top: 70px; position: static; } .background-image { background-size: cover; background-repeat: no-repeat; position: fixed; left: 0; right: 0; z-index: -1; width: 100%; min-height: 100%; } #card { margin-top: 100px; padding-top: 0.5%; padding-bottom: … -
When deploying on pythonanywhere i followed all stepts but still get the default pythonanywhere page
I did all the stepts from the documentation but still get the pythonanywhere default page, and I do not even know from where is coming since is not in my wsgi. Below is my wsgi, anyone has any clue? Thanks import os import sys path = '/home/andercorobert/agile-project/app' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'agile.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Tried to do it several times and also did changes to virtualenv and so on. -
What should I do to add multiple buttons in a Django app
I am trying to add 3 buttons in my django app 1. Generate Morse code 2. Add to cart 3. Buy Now I tried working on one button Add to cart but it is not posting.(I am a noob) I am adding my code for further reference. Views.py file # morsecode/views.py from django.shortcuts import render from .forms import MorseCodeForm MORSE_CODE_DICT = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', ', ': '--..--', '.': '.-.-.-', '?': '..--..', '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-' } def text_to_morse(text): morse_code = [] for char in text.upper(): if char == ' ': morse_code.append(' ') else: morse_code.append(MORSE_CODE_DICT.get(char, char)) return '\n'.join(morse_code) def morsecode_converter(request): input_text = '' morse_code = '' if request.method == 'POST': form = MorseCodeForm(request.POST) if form.is_valid(): input_text = form.cleaned_data['text_input'] morse_code = text_to_morse(input_text) else: form = MorseCodeForm() return render(request, … -
Implement a 50% discount on the second item in the shopping cart with django
Maybe someone can help me here. I want to implement a discount on my e-commerce project where the user gets a 50% discount on the cheapeast items when adding more than 1 item to the shopping cart. so, if a user adds to the shopping cart: ITEM1 (50€) and ITEM2(40€) SHOPPING CART: ITEM 1 - 50€ || Subtotal: 50€ ITEM 2 - 40€ || Subtotal: 20€ _______________ TOTAL: 70€ someone? Thanks! -
Getting DEFAULT_FILE_STORAGE/STORAGES are mutually exclusive when upgraded to 4.2
We are in process to upgrade to django 4.2. However we are facing above issue in running django peroject. We have already setup new way of STORAGES in settings.py i.e. STORAGES = { "staticfiles": {"BACKEND": "custom.core.storage.GzipManifestStaticfilesStorage"}, "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, } But its not working and getting said error in running project. But, when we manually go and remove DEFAULT_FILE_STORAGE from django\conf\global_settings.py file then at least it doesn't give above issue. Any suggestion(s) how to fix it, thanks! -
Django : automatic retry of failed database operations
Database operations can fail because of temporary network errors or because the database is temporarily unavailable. Is there a way to automatically retry the operation in these cases ? The documentation of Google's managed database offering states that connection pooling systems should reconnect to the database if a connection is in a bad state, and applications should retry a database transaction if an error app in the middle of a transaction. (See https://cloud.google.com/sql/docs/postgres/manage-connections, section "Exponential backoff") How can I implement this advise using Django? I'm currently having problems with views that successfully perform some database operations but randomly encounter a connection error during a subsequent database operation. How can I retry the database operation so that the view is finally rendered successfully? -
Status code 400 (Bad Request) with Django API tests
I'm working on a project with Django as framework and poetry as manager. Running some tests I found some problems with my viewsets, but I don't know exactly where it is. That is the error traceback I'll paste here the tests, viewsets and models codes: That's the code from my 'test_orderviewset.py' file That's the code from my 'test_productviewset.py' file That's the code from my 'models.py' file And the code from serializers I created: class ProductSerializer(serializers.ModelSerializer): category = CategorySerializer(required=True, many=True) category_id = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all(), write_only=True, many=True) class Meta: model = Product fields = ['title', 'description', 'price', 'active', 'category', 'category_id'] extra_kwargs = {'category': {'required': False}} def create(self, validated_data): category_data = validated_data.pop('category_id') product = Product.objects.create(**validated_data) for category in category_data: product.category.add(category) return product class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'title', 'slug', 'description', 'active', ] extra_kwargs = {'slug': {'required': False}} class OrderSerializer(serializers.ModelSerializer): product = ProductSerializer(required=True, many=True) products_id = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), write_only=True, many=True) total = serializers.SerializerMethodField() # Model function method def get_total(self, instance): total = sum([product.price for product in instance.product.all()]) return total def create(self, validated_data): products_data = validated_data.pop('products_id') user_data = validated_data.pop('user') order = Order.objects.create(user=user_data) for product in products_data: order.objects.add(product) return order class Meta: model = Order fields = ['product', 'total', 'user', 'products_id'] extra_kwargs = … -
Change the main database to Test when using Pytest
Help me solve the problem Here is my settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": ENV.MYSQL_DSN.path.lstrip("/"), "USER": ENV.MYSQL_DSN.user, "PASSWORD": ENV.MYSQL_DSN.password, "HOST": ENV.MYSQL_DSN.host, "PORT": ENV.MYSQL_DSN.port, }, 'test': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } Here is my test_api.py: import json import pytest from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient @pytest.fixture def api_client(): return APIClient() def test_proxys(api_client): url = reverse("gelet") response = api_client.get(url) assert response.status_code == status.HTTP_200_OK assert response["Content-Type"] == "text/html; charset=utf-8" assert b"<html>" in response.content @pytest.mark.django_db def test_generate_report(api_client): url = reverse("generate_report") data = { "dates": "01/01/2021 - 03/01/2021", "ip": "127.0.0.1", } response = api_client.post( url, data=json.dumps(data), content_type="application/json", ) assert response.status_code == status.HTTP_200_OK assert response.json() == {"status": "started"} How can I force autotests to use the test database test? It is important for me to understand which method can work. Please advise something. If there is an option with separate creation of a Postgres database, for example, this is also a suitable option I tried to use sqlite3 by creating it directly in the program code, but something didn’t work out import sqlite3 def run_sql(sql): conn = sqlite3.connect(':memory:') cur = conn.cursor() cur.executescript(sql) conn.commit() conn.close() @pytest.fixture(scope='session') def django_db_setup(): … -
Django - Naive datetime field to time zone
I'm using Django to build an web app and I have a shift in datetime datas when I upload them. In settings.py I specify : TIME_ZONE = 'CET' USE_TZ = True When I upload data like 29/01/2024 14:00:00 , I have this message : DateTimeField my_table.date received a naive datetime while time zone support is active In the PostgreSQL database, datas are stored in UTC not CET, in my example: 2024-01-29 13:00:00+00 Django interpret naive datetime in UTC not in CET (UTC+1) despite my settings.py TIME_ZONE parameter. How can I define that datas are CET and store 2024-01-29 13:00:00+01 ? -
Problems with virtual env on django project
.venv/bin/activate : O termo '.venv/bin/activate' não é reconhecido como nome de cmdlet, função, arquivo de script ou programa operável. Verifique a grafia do nome ou, se um caminho tiver sido incluído, veja se o caminho está correto e tente novamente. No linha:1 caractere:1 .venv/bin/activate That, and more functions that i type when i started my project in django. I started a new project and i simply dont know what is happening. i tried to activate with ~.venv/bin/activate~ and all, but everything gives me the same error message -
form post function is not working django python
am new to python and starting with Django Blog project, with admin area the blog post submit successfully, trying to design a page outside admin control area with limited functionality. so far i try with this code View.py from blog.forms import BlogPostForm def new_post(request): if request.method == 'POST': form = BlogPostForm(data=request.POST, files=request.FILES) if form.is_valid(): blgpstfrm = form.save(commit=False) blgpstfrm.author = request.user blgpstfrm.slug = f"{(blgpstfrm.title)}" blgpstfrm.save() obj = form.instance return render(request, "blog/in/new_post.html", {'obj':obj}) else: form = BlogPostForm() return render(request, "blog/in/new_post.html", {'form':form}) Forms.py class BlogPostForm(forms.ModelForm): body = forms.CharField(widget=CKEditorUploadingWidget()) class Meta : model = BlogPost fields = {'title', 'slug', 'body', 'features_image','tags'} New_post.html <form method="POST">{% csrf_token %} <h1>Add New Blog</h1> {{form.media}} <div class="new-post-title">{{form.title}}</div> <div class="sidebar"> <div class="new-post-feature-image">{{form.features_image}}</div> <div class="new-post-tags">{{form.tags}}</div> </div> <div class="new-post-content">{{form.body}}<br/>{{form.slug}} </div> <button type="submit" class="button">publish</button> </form> </div> their is no error in terminal or pages after submit. but when checking in post page no post present other then the admin area posts. -
cropping image only works by triggering second time save method
I have a django application. And I try to crop an high resolution image to a smaller resolution image. The problem I am facing is that cropping the image only works when the save method is triggered for the second time. So not the first time when I trigger the save method. So in models.py I have an image property: images = models.ImageField( upload_to="media/photos/animals", blank=True, null=True, verbose_name="Foto") And the save method looks like: def save(self, *args, **kwargs): self.slug = slugify(self.name) if self.pk is not None: orig = Animal.objects.get(pk=self.pk) if self.images: if orig.images != self.images: # Perform the crop if the image is updated with a different image im = Image.open(self.images) # To standardize your color space if not already RGB im = im.convert("RGB") exif = None if 'exif' in im.info: # Exif data records orientation, among other things exif = im.info['exif'] output = BytesIO() square = 200 # Set the dimension x_final, y_final = square, square # Get image dimensions width = im.size[0] height = im.size[1] if width > height: # crop the largest square out of the center of a landscape image and resize x1 = (float(width/2)-float(height/2)) y1 = (height - height) x2 = ((float(float(width/2)-float(height/2))) + height) y2 = … -
How to make a proxy model's relationships return proxy models themselves
I've got a simple model relationship: class Author(models.Model): ... class Book(models.Model): author = models.ForeignKey(Author) ... but I've also got some proxy models building on top of those models: class ProxyAuthor(Author): class Meta: proxy = True class ProxyBook(Book): class Meta: proxy = True Is there a way to get ProxyAuthor.objects.get(pk=123).books() to return ProxyBook objects rather than Book objects? -
accesing request.user in a tabularinline
I have a ModelForm with multiple TabularInlines that I want to use in the admin. I want to know which user changed something using the inlines. class ResourceForm(forms.ModelForm): resource = forms.FileField(widget=CustomImageFile, ...) class Meta: model = Resource fields = ["resource"] def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") super().__init__(*args, **kwargs) self.fields["resource"].widget.form_instance = self def clean(self): # i need the request.user here class ResourceTabularInline(TabularInline): model = Resource form = ResourceForm def get_formset(self, request, obj=None, **kwargs): formset = super().get_formset(request, obj, **kwargs) formset.user = request.user # <-- I hoped this would be in the kwargs later on return formset class FooAdmin(admin.ModelAdmin): inlines = [ResourceTabularInline,] unfortunately the key user is not in the kwargs of the __init__() method this way -> KeyError. How can I access the user -
Filter queryset based on values in the other queryset
I have the following model in django: class EmailSubscriber(BaseSubscriber): email = models.EmailField() name = models.CharField() Now let's say I made a queryset from EmailSubscriber Like below: queryset1 = EmailSubscriber.objects.all() Now I create another queryset like below: queryset2 = EmailSubscriber.objects.filter(some filters) I want to exclude those fields in queryset1 that have their email and name in queryset2. I mean, if a record in queryset1 has {"email": "john@gmail.com", "name": "john"} and there is a record in queryset2 with {"email": "john@gmail.com", "name": "john"}, the record in queryset1 must be excluded. So they must be unique together. How can I do that in an efficient way? Thanks in advance -
Django Beanstalk connection refused Error 502 no module named application
Ive been going back and forth with this. Like many in this context, I followed this guide. It worked when creating a skeleton django app but when applied to my existing local app, Im getting this error ModuleNotFoundError: No module named 'application' platform: Python 3.9 running on 64bit Amazon Linux 2023 this is my working directory pytrade .(Project Directory) ├── .ebextensions │ └── django.config ├── .elasticbeanstalk │ ├── config.yml │ ├── .gitignore ├── README.md ├── api (created app) │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── dataMethods │ ├── migrations │ ├── models.py │ ├── questrade_api │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── pytrade │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── requirements.txt wsgi.py """ For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pytrade.settings') application = get_wsgi_application() django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: pytrade.wsgi:application The WSGIpath is pointing to the right directory and file as far as I can tell. -
celery task not running when an object is declared , I am using def save_model function to call celery task as per requirement upon save
[2024-01-29 07:23:52,962: ERROR/MainProcess] Process 'ForkPoolWorker-16' pid:2871 exited with 'signal 11 (SIGSEGV)' [2024-01-29 07:23:54,730: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV) Job: 0.') Traceback (most recent call last): File "/Users/asim/Django/Practice-tool-ai-backend/ptenv/lib/python3.12/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost raise WorkerLostError( billiard.einfo.ExceptionWithTraceback: """ Traceback (most recent call last): File "/Users/asim/Django/Practice-tool-ai-backend/ptenv/lib/python3.12/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost raise WorkerLostError( billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV) Job: 0. """ The above mentioned is an error I am getting in celery task I have a requirement to call openai API in django admin save_model function So when an admin user adds a listening task , I retrieve the transcript and pass it to the openai API to generate questions and store them in database. Which was previously workin perfectly fine , since openai takes a lot of time to return response I put that part of the code in the celery background task to save admin time .. but ran into that issue More over if i remove that code #tasks.py @shared_task def sleeptime(time, obj_id): sleep(time) try: obj = ListeningTask.objects.get(id=obj_id) # Continue with processing using the retrieved object transcript = obj.transcript print(transcript) except ObjectDoesNotExist: print(f"Object with ID {obj_id} does not exist.") and just leave the function …