Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django full text search taggit
My application - the basics I have a simple django application which allows for storing information about certain items and I'm trying to implement a search view/functionality. I'm using django-taggit to tag the items by their functionality/features. What I want to implement I want to implement a full text search which allows to search across all the fields of the items, including their tags. The problem(s) On the results view, the tagged items are showing up multiple times (one occurence per tag) The ranking is correct when I specify * only a single* tag in the search field, but when I specify multiple tag names, I will get unexpected ranking results. I suspect the SearchVector() does not resolve the tags relation as I expected it to do. The tags should be treated just like a list of words in this case. Example Code models.py from django.db import models from taggit.managers import TaggableManager class Item(models.Model): identifier = models.SlugField('ID', unique=True, editable=False) short_text = models.CharField('Short Text', max_length=100, blank=True) serial_number = models.CharField('Serial Number', max_length=30, blank=True) revision = models.CharField('Revision/Version', max_length=30, blank=True) part_number = models.CharField('Part Number', max_length=30, blank=True) manufacturer = models.CharField('Manufacturer', max_length=30, blank=True) description = models.TextField('Description', blank=True) tags = TaggableManager('Tags', blank=True) is_active = models.BooleanField('Active', default=True) forms.py … -
"detail": "Authentication credentials were not provided." Django DRF
Im trying to create an api for my django project to get some data from database and show it as restframework Response everytime I try to get the data it shows me this error this is my views.py code for getting the data class QuestionListView(APIView): permission_classes = [IsAuthenticated] def get(self: Self, request: HttpRequest) -> Response: questions_list: Question = Question.objects.filter(status=True) if (len(questions_list) == 0): return Response('هنوز سوالی طرح نشده', status=status.HTTP_204_NO_CONTENT) else: serializer = QuestionsSerializer(instance=questions_list, many=True) return Response(serializer.data, status=status.HTTP_200_OK) this is my question model models.py file class Question(models.Model): CHOISES: list = [ ('option1', 'گزینه اول'), ('option2', 'گزینه دوم'), ('option3', 'گزینه سوم'), ('option4', 'گزینه چهارم'), ] SCALES: list = [ (1, 'آسان'), (2, 'متوسط'), (3, 'سخت'), ] question = models.CharField(max_length=200, unique=True, verbose_name='سوال') option1 = models.CharField(max_length=50, verbose_name='گزینه اول') option2 = models.CharField(max_length=50, verbose_name='گزینه دوم') option3 = models.CharField(max_length=50, verbose_name='گزینه سوم') option4 = models.CharField(max_length=50, verbose_name='گزینه چهارم') answer = models.CharField(max_length=10, choices=CHOISES, verbose_name='پاسخ', help_text='گزینه درست را انتخاب کنید') scale = models.IntegerField(choices=SCALES ,null=True, verbose_name='سطح سختی سوال') status = models.BooleanField(default=False, help_text='وضعیت انتشار سوال', verbose_name='وضعیت') def __str__(self): super(Question, self).__str__() return self.question class Meta: verbose_name = 'سوال' verbose_name_plural = 'سوالات' and this is the serializer.py file class QuestionsSerializer(serializers.ModelSerializer): class Meta: model = Question exclude = ('status',) read_only_fields = ('id',) and this is my … -
Issue with dictionary values not appending in Django session
I'm encountering an issue with updating dictionary values in Django session. Initially, I was using a list to store data in the session, and it worked perfectly fine. However, when I switched to using a dictionary to store the data, I noticed that the values were not getting appended as expected. Instead, the new data was replacing the old data in the dictionary. views.py: def pushups(request): if "record" not in request.session or not isinstance(request.session["record"], dict): request.session["record"] = {} return render(request, ("App_4/record.html"), { "record" : request.session["record"] }) def add(request): if request.method == 'POST': form = Add_record_form(request.POST) if form.is_valid(): a = form.cleaned_data["add_form"] b = request.session["record"] b[f"{date.year}-{date.month}-{date.day} {date.hour}:{date.minute}:{date.second}"] = a request.session["record"] = b return HttpResponseRedirect(reverse("App_4:view_record")) else: return render(request, "App_4/add_record.html", { "add_form" : form }) return render(request, ("App_4/add_record.html"), { "add_form" : Add_record_form() }) record.html {% for key,value in record.items %} <tr> <td>{{key}}</td> <td>{{value}}</td> </tr> {% empty %} <tr> <td>no tasks</td> </tr> {% endfor %} The strange thing is that the dictionary values only get updated correctly if I make changes in the views.py file or just simply click CTRL+S before adding new data. Otherwise, the previous data just gets replaced. This issue wasn't present when I was using a list instead of a dictionary. … -
Nested for loop - model.id in parent for loop does not match model.id in nested for loop (django)
I am trying to access data from a parent to a child via a foreign key. WHAT WORKS - the views The data in the child is not "ready to be used" and need to be processed, to be represented in a progress bar in %. The data processing is handled in the views. When I print it on the console, it seems to work and stored into a variable reward_positions. Reward positions = [(<Venue: Venue_name>, reward_points, reward_position_on_bar)] So this part works. The plan is therefore to access reward_position_on_bar by calling {{reward_positions.2}} WHAT DOESNT WORK - the template But something is not working to plan in the template. The template renders the last child_model (thats rewardprogram) objects of the last parent_id (thats venue) irrespective of the actual parent_id processed in the for loop. TEST RESULT & WHERE I THINK THE PROBLEM IS I think my problem lies in my nested forloop. The parent_id in the parent forloop does not match the '{{reward_position.0}}' in the nested forloop. Doing a verification test, {{key}} should be equal to {{reward_position.0}} as they both go through the same parent forloop. However, if {{key}} does change based on venue.id (parent forloop id), {{reward_position.0}} is stuck to … -
Django orm filter many to many fields
The question is this. There are Project and User models. In the Project model, there are 2 ManyToMany links to the users model. class Project(models.Model): name = models.CharField(max_length=100) content = models.TextField() creaters = models.ManyToManyField('User', related_name='creater_projects') workers = models.ManyToManyField('User', related_name='worker_projects') class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) I need to filter the projects depending on the transferred user.id You can filter as follows from django.db.models import Q user_id = 1 Project.objects.filter(Q(creaters__id=user_id) | Q(workers__id=user_id)) What other ways are there to do similar filtering? -
Applying sync_to_async for django query results in the same error nonetheless
I have the following code import asyncio from asgiref.sync import sync_to_async from user.models import Users @sync_to_async def get_users(input): return Users.objects.values_list("name", flat = True).filter( name__icontains=input) async def user_autocompletion(current: str): print(list(await get_users(current))) asyncio.run(user_autocompletion("b")) I am getting this error even though I used sync_to_async as advised django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How do I fix it? -
Troubleshooting: Cannot post images to S3 Bucket from Django during deployment on Vercel
So, I have been trying to use django admin panel to add some contents along with title and image into a database which I have been using in my react project. When I try to upload static file like image from django backend It is properly posted in s3 bucket. But in deployment its not working Also, the static files are properly retrieved as well in deployment as I can see css in django admin panel as well. Error message I am getting in deployment -
Django does not serve static files for ckeditor in docker container
I am deploying an django project with docker-compose and nginx. I can serve the ckeditor with its toolbar showing with python manage.py runserver. However when I try to serve it docker-compose and nginx I cant. These are the output in the console: Failed to load resource: the server responded with a status of 404 (Not Found) ckeditor-init.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) ckeditor.js:1 docker-compose.yml version: '3.8' services: db: image: postgres:13 environment: - POSTGRES_DB=db - POSTGRES_USER=user - POSTGRES_PASSWORD=password volumes: - db_data:/var/lib/postgresql/data networks: - app_network web: build: . command: gunicorn okuyorum.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/app/staticfiles - media_volume:/app/media expose: - 8000 depends_on: - db networks: - app_network nginx: image: nginx:1.19 volumes: - static_volume:/usr/share/nginx/html/static - media_volume:/usr/share/nginx/html/media - ./nginx.conf:/etc/nginx/nginx.conf ports: - 80:80 depends_on: - web networks: - app_network volumes: db_data: static_volume: media_volume: networks: app_network: Dockerfile # Use an official Python base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Create and set the working directory RUN mkdir /app WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y \ libpq-dev \ gcc \ gettext \ && rm -rf /var/lib/apt/lists/* # Install project dependencies COPY requirements.txt /app/ … -
Is there is a way to convert django project to app(iso/apk)
can I convert a django project into a iso/apk app, I have seen cordva that fixs this problem, but im not sure if it works with django since it use templates/assest/static folders, and cordva dosnt have this files system.., so is there is a way to config cordva to work with djanog or is there is another way? note: i do not prefer to rebuild the UI, I prefer to keep it as it is. a way to run the django project as an application. -
I get 301 Moved Permanently Error when react app calls a channel route of django app
I use django-eventstream and django channel packages for have a realtime channels and when channel route is called by Browser i would get Sent messages in my channel(i can see messages in browser tab), but react-app gets 301 Moved Permanently Error when calls my channel with this form new EventSource('http://source-ip:source-port/post-list', { withCredentials: true }); my setting for django-app : 1)installing django--eventstream 2)installing django channel 3)Adding them in 'INSTALLED_APPS' part of settings.py 4)Adding the GripMiddleware: in MIDDLEWARE part of settings.py 5)creating an asgi.py : import django from django.core.asgi import get_asgi_application from django.urls import path, re_path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import django_eventstream os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myserver.settings') os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" application = ProtocolTypeRouter({ 'http': URLRouter([ path('events/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['test'] }), path('post-list/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns)), { 'channels': ['post'] }, ), re_path(r'', get_asgi_application()),]), }) 6)using send_event for sending message to channel: send_event('post', 'message', {'text': 'hello world' }) -
Queryset to update set of values for a field
What queryset can I use to translate the values of a field from one set of values to another set? For example, lets say I have a User model with a CharField containing the name of a country and I wish to update the name of some of the countries for all users using the following dict: new_country_names = {"Micronesia": "States of Micronesia", "Macedonia": "North Macedonia"} I obviously want to avoid doing this by looping over each user and checking the value of their country. -
I get 301 Moved Permanently Error when react app calls my channel route of django app
I get 301 Moved Permanently Error when react app calls my channel route of django app. I use django-eventstream and django chnnel packages for have a realtime channels and when channel route is called by Browser ,i would get Sent messages in my channel(can see messages in browser tab), but react-app gets 301 Moved Permanently Error when calls my channel with this form enter image description here my setting for django-app : 1)installing django-eventstream and django channel packages 2)Adding them in INSTALLED_APPS section and Adding the GripMiddleware to MIDDLEWARE part in settings.py file 3)creating an asgi.py enter image description here 4)using send_event for sending message to channel enter image description here 5)django-cors-headers package is also used -
Images and static files not showing up on Django app with Docker Compose and Nginx
When I run Django application in docker compose containers and deploy to the server I have no images displayed on the page and no statics for the admin panel. docker-compose.yml version: '3.3' services: db: image: postgres:13.0-alpine volumes: - db_data:/var/lib/postgresql/data/ env_file: - ./.env web: image: login/foodgram:latest restart: always volumes: - static_value:/app/static/ - media_value:/app/media/ depends_on: - db env_file: - ./.env frontend: image: login/foodgram_frontend:latest volumes: - ../frontend/:/app/result_build/ depends_on: - web nginx: image: nginx:1.21.3-alpine restart: always ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf - ../frontend/build:/usr/share/nginx/html/ - ../docs/:/usr/share/nginx/html/api/docs/ - static_value:/var/html/static/ - media_value:/var/html/media/ depends_on: - web volumes: static_value: media_value: db_data: nginx.conf server { server_tokens off; listen 80; server_name my ip; client_max_body_size 20M; location /api/docs/ { root /usr/share/nginx/html; try_files $uri $uri/redoc.html; } location /media/ { root /var/html/; } location /static/admin/ { root /var/html/; } location /static/rest_framework/ { root /var/html/; } location /admin/ { proxy_pass http://web:8000/admin/; } location /api/ { 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; proxy_pass http://web:8000; } location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri /index.html; 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; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /var/html/frontend/; } } Please help, third day i can't … -
Django - problem re-adding goods to the basket
I am creating an online store on Djnago. The project has a basket in which you can place goods, as well as remove them. Goods are placed and removed without problems. But, after the product has been placed, after deletion - when re-adding this product (which was deleted) to the basket (the user is always the same) - the product does not appear, what is the problem? Below is the code of all application files: models.py: from django.db import models from users.models import User class ProductCategory(models.Model): name = models.CharField(max_length=128, unique=True) description = models.TextField(null=True, blank=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=256) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveSmallIntegerField(default=0) image = models.ImageField(upload_to='products_images') category = models.ForeignKey(to=ProductCategory, on_delete=models.CASCADE) def __str__(self): return f'Product: {self.name} | Category: {self.category.name}' class Basket(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) product = models.ForeignKey(to=Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=0) created_timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Корзина для {self.user.username} | Продукт: {self.product.name}' views.py: from django.shortcuts import render, HttpResponseRedirect from products.models import ProductCategory, Product, Basket from users.models import User def index(request): context = { 'title': 'Store', 'is_prom': True, } return render(request, 'products/index.html', context) def products(request): context = { 'title': 'Store - Каталог', 'products': Product.objects.all(), 'categories': ProductCategory.objects.all(), } return render(request, "products/products.html", … -
Django sessions idle on localhost, pending forever after login callback
Django project cannot set sessions only on localhost, and the web keeps pending forever after login callback. Here is the log: "GET / HTTP/1.1" 302 0 "GET /kc/callback?state=95ad23ff24f648dd9a28b845dab57623&session_state=feac8cb3-a655-4608-82b5-2a309e97db72&code=771863de-fa31-4aa7-a936-c26c082995e1.feac8cb3-a655-4608-82b5-2a309e97db72.d52c4c80-ab1f-4a3c-9909-f1d43de72c5c HTTP/1.1" 302 0 "GET /kc/callback?state=3c3f804074094bccb802dfb65b8eb34f&session_state=feac8cb3-a655-4608-82b5-2a309e97db72&code=d1ae63ae-9c6e-4fb3-b2b6-75ac7f339a0d.feac8cb3-a655-4608-82b5-2a309e97db72.d52c4c80-ab1f-4a3c-9909-f1d43de72c5c HTTP/1.1" 302 0 setting user session Internal Server Error: / Traceback (most recent call last): File "C:\Users\...backend\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 233, in _get_session return self._session_cache AttributeError: 'SessionStore' object has no attribute '_session_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\...backend\venv\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\...backend\venv\lib\site-packages\django\utils\asyncio.py", line 33, in inner return func(*args, **kwargs) File "C:\Users\...backend\venv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\...backend\venv\lib\site-packages\django\utils\asyncio.py", line 33, in inner return func(*args, **kwargs) File "C:\Users\...backend\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\...backend\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: sorry, too many clients already The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\...backend\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\...backend\ilumens_backend_sf\middleware\auth.py", line 164, in __call__ if "user" not in request.session: File "C:\Users\...backend\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 55, in __contains__ return key in self._session File "C:\Users\...backend\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 238, in _get_session self._session_cache = self.load() File "C:\Users\...backend\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load s … -
How do I run a Django GitHub workflow CI with .env file for secret management
I have my django project using a local .env file on my windows computer that never gets committed to the repo. However, for GitHub CI testing it needs to read the secrets for the settings.py from somewhere and since it doesn't have the .env file it cannot run any tests and crashes. How would I solve this problem? I am using python-dotenv package to read my secrets from the .env local file when developing. I basically want to run tests automatically on my GitHub repo on every push to main branch with secret management. The only solution that I could find was to create a .env file within the GitHub workflow as a step before running the test, but that is a bit crummy because then you are leaking out your .env fields and what exists on there. - name: Create .env file run: | echo "SECRET_KEY=123456" > .env .... How should I solve this problem? -
Celery is not consuming with two tasks together
sorry, I am a rookie to celery. I have 3 celery snippet as follows: first define the Task Class in celery_tasks.tasks.py import celery class LoggerDefine(celery.Task): name = 'message-logger' def run(self, payload): pass class PerformanceMeasureDefine(celery.Task): name = 'performance-logger' def run(self, payload, elapseTime):): pass then implement the methods in from consumers.logger import django django.setup() from log_models.models import Level_logs from django.conf import settings from common_functions.logger import * from celery_tasks.tasks import LoggerDefine, PerformanceMeasureDefine class LoggerImpl(LoggerDefine): def run(self, payload): fmt1 = 'Message body: {}' print("-------------------------------- log persistor consuming --------------------------------") Level_logs.objects.create( level=payload.get(LEVEL), date_time=payload.get(DATETIME), file_name=payload.get(FILENAME), line_number=payload.get(LINE_NUMBER), function_name=payload.get(FUNCTION), payload=payload.get(PAYLOAD), ) return fmt1.format(payload) class PerformanceMeasureImpl(PerformanceMeasureDefine): def run(self, payload, elapseTime): fmt1 = 'Message body: {}' print("-------------------------------- performance consuming --------------------------------") print("payload = ", payload) print("elapseTime = ", elapseTime) return fmt1.format(payload) finally, I instantiate them as two consumers from consumers.logger import LoggerImpl, PerformanceMeasureImpl from celery_tasks.utils import create_worker_from logger, _ = create_worker_from(LoggerImpl) logger.worker_main(["worker", "-c", "2"]) performance_measure, _ = create_worker_from(PerformanceMeasureImpl) performance_measure.worker_main(["worker", "-c", "2"]) then it is not working, I tried to comment out performance_measure and leave only logger like: from consumers.logger import LoggerImpl, PerformanceMeasureImpl from celery_tasks.utils import create_worker_from logger, _ = create_worker_from(LoggerImpl) logger.worker_main(["worker", "-c", "2"]) #performance_measure, _ = create_worker_from(PerformanceMeasureImpl) #performance_measure.worker_main(["worker", "-c", "2"]) then logger works properly. I also tried comment out logger and leave … -
Django ORM - 'annotate' and 'order_by' doesn't seem to work equivalently to 'GROUP BY' and 'ORDER BY'?
Summary: ordered_tags = tagged_items.annotate(freq=Count('tag_id')).order_by('-freq') for i in ordered_tags: print(i.tag_id, i.tag, i.freq) This does not work equivalently to GROUP BY tag_id ORDER BY COUNT(tag_id) DESC. Why? Using Django ORM, I am trying to do something like: SELECT tag_id, COUNT(tag_id) AS freq FROM taggit_taggeditem WHERE content_type_id IN ( SELECT id FROM django_content_type WHERE app_label = 'reviews' AND model IN ('problem', 'review', 'comment') ) AND ( object_id = 1 OR object_id IN ( SELECT id FROM review WHERE problem_id = 1 ) OR object_id IN ( SELECT c.id FROM comment AS c INNER JOIN review AS r ON r.id = c.review_id ) ) GROUP BY tag_id ORDER BY freq DESC; So here's what I have contrived: querydict_for_content_type_id = { 'current_app_label_query' : Q(app_label=ReviewsConfig.name), 'model_name_query' : Q(model__in=['problem', 'review', 'comment']) } # used in content_type_query query_for_content_type_id = reduce(operator.__and__, querydict_for_content_type_id.values()) # Query relevant content_type from TaggedItem model. content_type_query = Q(content_type_id__in=ContentType.objects.filter(query_for_content_type_id)) # Query relevant object_id from TaggedItem model. object_query = Q(object_id=pk) | Q(object_id__in=problem.review_set.all()) for review in problem.review_set.all(): object_query |= Q(object_id__in=review.comment_set.all()) tagged_items = TaggedItem.objects.filter(content_type_query&object_query) # JOIN Tag # tags = tagged_items.select_related('tag') # GROUP BY freq ORDER_BY freq DESC; ordered_tags = tagged_items.annotate(freq=Count('tag_id'))#.order_by('-freq') for i in ordered_tags: print(i.tag_id, i.tag, i.freq) Django ORM doesn't work as intended. Calling distinct method on ordered_tags … -
Django ManyToMany relationships not being saved in initial create, but saved on update - how to fix?
en mi archivo models.py tengo dos clases Curso y Carreras, en el primero de ellos tengo un campo que es una relacion del tipo ManyToMany con el segundo. El problema que tengo es que cuando voy a crear un objecto para el modelo Curso y hago las relaciones pertinentes estas no son guardadas en la base de datos, sin embargo cuando ese objeto que creo le quiero modificar la relacion ManyToMany es cuando si guarda en la base de datos la relacion, pero la que guarda e la introduje inicialmente cuando creaba el objeto. lo que quiero es que una vez creado el objeto esta relacion sea guardada correctamente y no se quede asi sin mas en el aire, porque de ella depende un calculo que hago posteriormente -
i am unable to proceed in the cousera course which is django specilization due to some errors
this is the error that I have received I was trying to reload in python everybody as I successfully created my virtual environment, but when I reload in the web, I am getting an error that I attached in the imageries would be thankful if someone help me to proceed this problem. -
Error running multiple Django production sites on Ubuntu 22.04/apache2
I am trying to host two virtual django sites on a ubuntu/apache2 setup. Site number one works great. I mirrored the settings for site number two but I am getting error: [Fri Jun 02 18:27:24.041306 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): Shutdown requested 'aww.exodustec.com'. [Fri Jun 02 18:27:24.048138 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): Stopping process 'aww.exodustec.com'. [Fri Jun 02 18:27:24.049208 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): Destroying interpreters. [Fri Jun 02 18:27:24.049751 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): Destroy interpreter 'aww.exodustec.com|'. [Fri Jun 02 18:27:24.050397 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): End interpreter 'aww.exodustec.com|'. [Fri Jun 02 18:27:27.588319 2023] [wsgi:info] [pid 22145:tid 140106201364352] mod_wsgi (pid=22145): Attach interpreter ''. [Fri Jun 02 18:27:27.668319 2023] [wsgi:info] [pid 22145:tid 140106201364352] mod_wsgi (pid=22145): Adding '/aww/src/' to path. [Fri Jun 02 18:27:55.908422 2023] [wsgi:info] [pid 22145:tid 140106168383040] mod_wsgi (pid=22145): Create interpreter 'aww.exodustec.com|'. [Fri Jun 02 18:27:55.913683 2023] [wsgi:info] [pid 22145:tid 140106168383040] mod_wsgi (pid=22145): Adding '/aww/src/' to path. [Fri Jun 02 18:27:55.914667 2023] [wsgi:info] [pid 22145:tid 140106168383040] [remote] mod_wsgi (pid=22145, process='aww', application='aww.exodustec.com|'): Loading Python script file '/aww/src/awwcollectables/wsgi.py'. [Fri Jun 02 18:27:56.567455 2023] [wsgi:error] [pid 22145:tid 140106168383040] [remote] mod_wsgi (pid=22145): Failed to exec Python script file '/aww/src/awwcollectables/wsgi.py'. [Fri Jun 02 18:27:56.567620 … -
Connection reset by peer on file upload if JWT expires
We have a django app and it supports a file upload request. The entire upload comprises multiple requests. We are authenticating with JWT and we have logic to handle a 401 and in that case use the refresh token to get a new access token and resend the failed request. However if the token expires between 2 requests of the same upload the 401 response never makes it to the client. In the logs I found that before nginx gets the response we get this error: 2023/06/02 16:23:11 [error] 1924925#1924925: *75 readv() failed (104: Connection reset by peer) while reading upstream, client: xx.xx.xx.xx, server: example.com, request: "POST /api/upload/ HTTP/1.1", upstream: "uwsgi://unix:///bar/foo/our_app/app.sock:", host: "", referrer: "http://example.com:8082/" This causes the client to get an empty response body and the browser throws a ERR_CONTENT_LENGTH_MISMATCH error. The entire upload takes under 10 minutes and we have all the timeouts set to 100 minutes: uwsgi_read_timeout 6000; uwsgi_connect_timeout 6000; uwsgi_send_timeout 6000; send_timeout 6000; proxy_read_timeout 6000; proxy_send_timeout 6000; What is causing the socket to get closed? How can I prevent that? Are there other timeouts I could set? Any logging that I can enable to see why the socket is getting closed? Is there a way to … -
Django model: Query of query or filter of filter
I have 2 models, and on the function, I need to filter in 'x' the users which has the id's equal the id's received. And secondly, I need to filter in another query (let's say 'y'), the description from model Detail, which has the person_id equal to the id's already filtered in 'x'. It's like a filter of a filter, or a query of a query. class Person(models.Model): user = models.ForeingKey(Users, on_delete=models.CASCADE) name = models.CharField(max_length=50) class Detail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) description = models.TextField() def test(request, id_user): x = Person.objects.filter(user_id = id_user) I don't know how to do it. I'm new to Python and Django. It would be something like this: y = Detail.objects.filter(person_id = id_x). But of course, this isn't right. Can someone help me? -
Object of type Product is not JSON serializable django
I have an ecommerce website and every time I try anything it gives me this error Object of type Product is not JSON serializable I've tried everything on stackoverflow, github and everything I could find on google but I didn't find anything and PickleSerializer just broke everything -
ModuleNotFoundError when importing my module and models.py from a Django app
I have an issue with this code import os from parser_main.parser_main.security_values import access_token os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parser_main.parser_main.settings') from parser_main.art_parser_app import models It raises an error ModuleNotFoundError: No module named 'security_values' The script works fine if I remove the line from parser_main.art_parser_app import models But I need both these modules