Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 4 Everybody: 405 Error, Auto-grader assignment Ad List #1
I'm following the DJ4E coursera course and I am on the 5th module auto-grader assignment: Ad List #1 When I run the auto-grader everything passes except the last test and I get this error: Logging out... Loading URL: https://loupy316.pythonanywhere.com/logout/?next=/ads/ (Open URL) Could not find HTML The current node list is empty. Here is my html: {% extends 'base_bootstrap.html' %} {% load app_tags %} <!-- see home/templatetags/app_tags.py and dj4e-samples/settings.py --> {% block navbar %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="border-radius:10px !important"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home:home' %}">LP's Site</a> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> {% url 'home:home' as home_url %} <a class="nav-link {% if request.get_full_path == home_url %}active{% endif %}" href="{% url 'home:home' %}">Home</a> {% url 'ads:all' as ads_url %} <li {% if request.get_full_path == ads_url %}class="active"{% endif %}> <a class="nav-link" href="{% url 'ads:all' %}" role="button">Ads</a> </li> </ul> <ul class="navbar-nav"> {% if user.is_authenticated %} <li> <a class="nav-link" href="{% url 'ads:ad_create' %}">Create Ad</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="rightnavDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <img style="width: 35px; height: 35px; border-radius: 50%; object-fit: cover;" src="{{ user|gravatar:60 }}"/><b class="caret"></b> </a> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="rightnavDropdown"> <li> <form method="post" action="/admin/logout/?next={% url 'ads:all' %}"> {% csrf_token %} <button type="submit" class="dropdown-item">Logout</button> </form> </li> </ul> </li> {% … -
Django 5.1 UserCreationForm won't allow empty passwords
I am upgrading a Django 3.0 app to 5.1 and have been moving slowly through each minor release. So far so good. However, once I upgraded from Django 5.0 to 5.1, I saw changed behavior on my "Create New User" page, which used to allow empty passwords, with a random password being generated if none is supplied. Now, I can no longer submit an empty password. I get a "required field" error on both the password fields, even though the fields are both explicitly set as required=False. I know there were some changes (5.1.0, 5.1.1) to the UserCreationForm class in Django 5.1. I tried using AdminUserCreationForm instead of UserCreationForm and setting the usable_password field to None, but it still won't allow empty passwords like before. Any ideas? Environment Python 3.12.8 Django 5.1.5 Simplified Code class SignupForm(AdminUserCreationForm): # previously using UserCreationForm usable_password = None # Newly added # Form fields sharedaccountflag = forms.ChoiceField( label='Cuenta compartida', required=True, choices=BOOLEAN_CHOICES ) # Constructor def __init__(self, *args, **kwargs): # Call base class constructor (i.e. SignupForm) super(SignupForm, self).__init__(*args, **kwargs) # Set password fields as optional self.fields['password1'].required=False self.fields['password2'].required=False # Set form helper properties self.helper = FormHelper() setFormHelper(self.helper) # set form method (POST / GET) and styling self.helper.form_tag … -
Using sessions in post requests django
I am currently trying to code my first website. I have a post request taking in answers from a form. I then try to save this information into the session and this doesn’t seem possible. Even when just editing the session data inside the request it doesn’t seem possible and I also can’t print to debug, this could be a stupid question as I am very inexperienced but I cannot find any solution or a reason why? -
Saving "last seen" time doesn't work beyond a few seconds
Based on this question I added the following middleware to track users' last seen date: from datetime import datetime, timedelta from dateutil.parser import parse from .models import User class LastSeenMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): last_seen = request.session.get("last-seen") now = datetime.now() too_old_time = now - timedelta(seconds=60) if not last_seen or parse(last_seen) < too_old_time: if request.user.is_authenticated: User.objects.filter(id=request.user.id).update(last_seen=now) request.session["last-seen"] = now.isoformat() return self.get_response(request) This works when I set the timedelta to only a few seconds, but anything more and it stops updating the field. Am I missing something obvious? -
Setting up Django in a subdirectory
I am trying to set up Django in a subdirectory (running under Apache2 through wsgi), but Django stops recognizing the static URLs. This is an example url, that gives me a 404: https:/<domain>/<subdirectory>/<appname>/en/static//img/favicon.png This should map to the filesystem here: /<projectpath>/<appname>/static/<appname>/img/favicon.png The development server (without a subdirectory) finds the file in the filesystem here: /<appname>/static/<appname>/img/favicon.png How do I setup django to recognize it's not running at / but at /<subdomain>/? -
How to show multiple objects in Django detailview
I have two models created, one Topic and another Entries. Listview showing all the Topics link. Clicking on each topic link will show all the entries related to that particular topic. I have created multiple entries for each Topic. DetailView only showing single entries for each topic link. How to show multiple entries for each topic link using DetailView? Models.py class Topic(models.Model): '''A topic that user will add the content about.''' title = models.CharField(max_length=200) class Entries(models.Model): '''Entries and Topic will have many to one relationship''' topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() image = models.ImageField(upload_to='images', blank=True) date_added = models.DateTimeField(auto_now_add=True) views.py class TopicListView(ListView): model = Topic template_name = 'cms_app/topic_list.html' context_object_name = 'topic' class ContentDetailView(DetailView): model = Entries urls.py urlpatterns = [ path('', TopicListView.as_view(), name = 'all-topic'), path('content/<int:pk>', ContentDetailView.as_view(), name = 'all-content'), ] Topic.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>All Topics</title> </head> <body> <h1>Topic List</h1> <h3> {% for data in topic %} <p><a href="{% url 'all-content' data.id %}">{{ data.title }}</a></p> {% endfor %} </h3> </body> </html> Entries.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>All Contents</title> </head> <body> <p>{{object.text }}</p> <p>{{object.image }}</p> <p>{{object.date_added }}</p> </body> </html> -
celery-container error (exited with code 1) after installing and adding django-crontab to INSTALLED_APPS in settings.py
I work on a django project, which needs celery for running some tasks in the background. I also need to run some cron-jobs, so I installed django-crontab into the container, added to the INSTALLED_APPS in settings.py, "python manage.py crontab show" OUTPUT: root@865809c7149e:/apps# python manage.py crontab show Currently active jobs in crontab: ab590d03e928be09c5fc1a0048404548 -> ('*/3 * * * *', 'AppName.cron.cron_job_method', '>> /apps/crontab.log') SADLY no crontab.log file appears... I don't understand why... AND: celery container exits on "docker compose up" with: ... celery-1 | ModuleNotFoundError: No module named 'django_crontab' celery-1 exited with code 1 web-1 | Watching for file changes with StatReloader Here my docker-compose.yml services: db: image: postgres:17 env_file: .env volumes: - ./local-db:/var/lib/postgresql/data redis: image: redis:7 web: build: . command: python manage.py runserver 0:8030 ports: - 8030:8030 volumes: - ./projectDIR:/apps env_file: .env links: - db depends_on: - db - redis celery: build: . command: celery -A projectDIR worker -l INFO env_file: .env volumes: - ./projectDIR:/apps environment: redis_url: redis://redis:6379/0 links: - db - redis - web depends_on: - web - redis ANY HELP IS VERY APPRECIATED! -
How can I configure a Django Unfold "custom site" with a required URL parameter?
I'm attempting to create a "custom site" using Django Unfold. I have an existing admin panel configured using the more basic ModelAdmin approach which works nicely. However, I need to create a separate admin panel using the "custom site" feature for use with django-tenants. I want the URL structure to look like: http://localhost:8000/tenant-admin/$tenant-id/. Within the "custom site", Django Tenants will scope the Postgres search path to the correct Postgres schema and the admin will be able to manage all of the models for a given tenant. I have defined my custom site as follows: from django.contrib import admin from django.urls import path from unfold.sites import UnfoldAdminSite from unfold.admin import ModelAdmin from tenant_app.models import Foo class TenantAdminSite(UnfoldAdminSite): # hopefully not needed -- but this is the first instance of admin:index causing problems # index_template = "admin/dashboard.html" def get_app_list(self, *args, **kwargs): # this lives at apps/tenant_app and is the only app that this TenantAdminSite # will use. Not sure if strings are valid here? return ["tenant_app"] def get_urls(self): """ Add custom URLs to the default admin site, capturing the tenant name. """ from django.urls import reverse # Capture the tenant name as part of the URL urls = super().get_urls() # Add custom … -
How to find user_id in Django endpoint
I have this Django endpoint: def get(http_request: HttpRequest, id: str): book_account_id = UUID(id) user_id: UUID = http_request.user.id affiliated_price_subscriptions = None response = BookAccountService.filter( id=book_account_id ).prefetch_related( Prefetch( 'subscription_set', queryset=SubscriptionRepository.filter( active=True ).prefetch_related( Prefetch( 'pricesubscription_set', queryset=PriceSubscriptionRepository.filter( Q(status=PriceSubscription.PriceSubscriptionStatus.PENDING) | Q(status=PriceSubscription.PriceSubscriptionStatus.REQUIRES_PAYMENT) ), to_attr='price_subscriptions' ) ), to_attr='subscriptions' ) ).first() affiliated_price_subscriptions = list(chain.from_iterable( subscription.price_subscriptions for subscription in response.subscriptions )) # The user must be part of the group that owns the book account # or the book acc must have at least one pending subscription if not PersonGroupService.exists( person__user_id=user_id, group__bookaccount__id=book_account_id ) and affiliated_price_subscriptions is None: return RestResponse( status=status.HTTP_200_OK, data=Response( code=24, error=True, messages=[ f"User with ID {user_id} does not have access to book account with ID {book_account_id}." ], data=None, ).to_dict(), ) return (...) Basically what it does is to get the book_account either if: the user.id belongs to a person that belongs to the group of that book_account. The book account has a related a related price-subscription with a PENDING or PENDING_PAYMENT status. I erased the is_authenticated: True since for 2) you do not need to be logged in to obtain the book_account data. However, when I call the endpoint while authenticated I get an error since user_id is null. I realized the only way to not have … -
Django Daphne not working with WSS, Ngnix and Docker
I'm trying to deploy an application built with Django and Daphne to open a WebSocket connection. Everything works perfectly on localhost, as I'm not using Nginx. However, in production, I need to use Nginx to serve SSL/HTTPS connections, including WSS. Unfortunately, it no longer works. When I try to use HTTPS on port 443, the WebSocket connection remains pending indefinitely until it eventually fails. I really considered removing Nginx because I found a Daphne configuration that runs on port 443 with an SSL certificate. daphne -b 0.0.0.0 -e ssl:443:privateKey=/privkey.pem:certKey=/fullchain.pem core.asgi:application However, I would still need Nginx to serve static files. I feel like I've tried everything so far. Can someone help me? docker-compose.yml services: web: build: . container_name: meetlink_django_app ports: - 8000:8000 - 8001:8001 volumes: - .:/app - static_volume:/app/core/staticfiles - ./certbot/conf:/app/certbot/conf:ro - ./certbot/www:/app/certbot/www:ro environment: - DEBUG=True - PYTHONUNBUFFERED=1 - DJANGO_SETTINGS_MODULE=core.settings - ENV=${ENV} networks: - meetlink-network command: - bash - -c - "python manage.py migrate && python manage.py runserver 0.0.0.0:8000 & daphne -b 0.0.0.0 -p 8001 core.asgi:application" depends_on: database: condition: service_healthy cache: condition: service_healthy database: image: postgres container_name: meetlink_django_database environment: - POSTGRES_USER=${DB_USERNAME} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} ports: - ${DB_PORT}:5432 volumes: - database_volume:/var/lib/postgresql/data networks: - meetlink-network healthcheck: test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER"] … -
500 server error with Django Rest Framework
I am using Django/DRF with Djoser and djangorestframework-simplejwt to create an API for full authentication including signup, login, activation, forgot password and reset password. I followed along with this YT tutorial For some reason, when I send a POST request in Postman to localhost:8000/api/users/ I am getting this error and I have no idea why at this point, django.db.utils.DatabaseError: Save with update_fields did not affect any rows. I'm not using SQLite but an actual Postgres db on localhost. I've tried changing user.save(self._db) to just user.save(), same error. I've updated Django to 5x. Django is the only one with a significant update compared to the tutorial, he uses Django 4x. I did move some of the original model code to a managers.py file based on this testdriven.io tutorial I've been able to run python manage.py runserver with no errors after doing so. It doesn't seem to be any code related to the tutorial but something with the python packages... Here is the error from the cli: [24/Jan/2025 16:40:07] "POST /api/users/ HTTP/1.1" 500 138392 Bad Request: /api/users/ [24/Jan/2025 17:05:47] "POST /api/users/ HTTP/1.1" 400 62 Internal Server Error: /api/users/ Traceback (most recent call last): File "/home/da/projects/full_auth_api/full_auth/backend/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) … -
Puppeteer not working with Django Viewset
I am trying to write a Django REST endpoint which will convert the HTML content to PDF and then return the Streaming file response to download the report. For this purpose, I am using Puppeteer, which works fine out of Django scope (e.g. for testing purpose). The download view minimal example is following import asyncio from pyppeteer import launch from django.http import HttpResponse from rest_framework.viewsets import ViewSet from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication class DownloadReport (ViewSet): permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] async def html_to_pdf(self, html): browser = await launch( headless=True, args=['--no-sandbox', '--disable-setuid-sandbox'] ) page = await browser.newPage() await page.setContent(html) await page.setViewport({ 'width': 1920, 'height': 1080, 'deviceScaleFactor': 1 }) pdf = await page.pdf({ 'format': 'A3', 'printBackground': True, 'landscape': True, 'scale': 1 }) await browser.close() return pdf def retrieve(self, request): content = "<h1>Hurrah PDF conversion successfull<h1>" content = asyncio.run(self.html_to_pdf(content)) response = HttpResponse(content, content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="report.pdf"' return response The problem is in Djanog the browser is neven launched it thrwos following exeption Traceback (most recent call last): File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 65, in … -
FormData file upload to Django model?
I'm trying to upload a file through a jQuery ajax request, using FormData. When I set processData and contentType to false, I get the error Forbidden (CSRF token missing.). When I remove those, I get the error Uncaught TypeError: 'slice' called on an object that does not implement interface Blob.. What am I missing here? $(".form").on("submit", function(event) { event.preventDefault(); $.ajax({ url: "/upload_profile_pic/", type: "POST", data: { "profile_pic": formData.get("file"), "csrfmiddlewaretoken": $(this).find("input[name='csrfmiddlewaretoken']").val() }, }, success: function (data) { console.log("success: "+data); }, error: function (data) { console.log(data); } }); }); -
Django vs PHP 8.*: Memory usage with 1000 concurrent visitors
I'm currently deciding between Django (Python) and PHP 8.* for a very large project that expects high traffic. Memory usage is a crucial factor for me since the website will need to handle a significant number of concurrent visitors. For example, let's say the site needs to handle 1000 concurrent visitors. Please consider that the project will be well optimized. From what I understand: PHP creates a new process for each request, which might lead to higher memory consumption under heavy load since each request is handled separately. Django, on the other hand, uses a persistent process to handle requests, which might help with better memory management but could also cause its own memory-related concerns under high traffic. I've asked ChatGPT for advice on this, but it gives random and wrong answers, so I don't trust it. I'm looking for insights or benchmarks that compare the memory usage of PHP and Django when handling high traffic and concurrent users. Specifically, how much memory each might use when handling around 1000 concurrent visitors, and any research on how each stacks up in terms of scalability and memory efficiency. Which language/framework would you recommend if memory usage is a key factor for … -
Arrows in Maplibre
Hey I am using maplibre for custom map, i am using geodjango for backend, data coming from database is { id: "arrow_tile_layer", type: "symbol", source: "arrow", 'source-layer': "line", minzoom: 16, maxzoom: 20, filter: ["==", ["get", "way_type"], "primary"], paint: {'text-color': '#000000', 'text-opacity': 0.8}, layout: {'text-font': ['Noto Sans Regular'], 'text-size': 12, 'text-field': '- > ', 'symbol-placement': 'line'}, } there isn't any error in the frontend however, in the map arrows is not visible I have tried to show the arrows in highway, but it is not visible -
"Token contained no recognizable user identification" when refreshing access token
i have the following setup for logging user in and giving out the access and refresh token, refresh token is set in cookies and the access_token is just handed out in json # login_views class UserLoginAPIView(APIView): class UserLoginInputSerializer(serializers.Serializer): username_or_email = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) class UserLoginOutputSerializer(serializers.Serializer): username = serializers.CharField(read_only=True) user_email = serializers.EmailField(read_only=True) full_name = serializers.CharField(read_only=True) is_verified = serializers.BooleanField(read_only=True) verification_required = serializers.BooleanField(read_only=True) user_type = serializers.ListField(child=serializers.CharField(), read_only=True) staff = serializers.BooleanField(read_only=True) superuser = serializers.BooleanField(read_only=True) access_token = serializers.CharField(read_only=True) def post(self, request, *args, **kwargs): input_serializer = self.UserLoginInputSerializer(data=request.data) input_serializer.is_valid(raise_exception=True) try: login_details, refresh_token = user_login( **input_serializer.validated_data ) except DjangoValidationError as e: return Response( { "success": False, "message": e.message, }, status=status.HTTP_401_UNAUTHORIZED, ) except ValidationError as e: return Response( { "success": False, "message": e.detail[0], }, status=status.HTTP_401_UNAUTHORIZED, ) except Exception as e: return Response( { "success": False, "message": str(e), }, status=status.HTTP_400_BAD_REQUEST, ) output_serializer = self.UserLoginOutputSerializer(login_details) response = Response( { "success": True, "message": "User log in successful.", "data": output_serializer.data, }, status=status.HTTP_200_OK, ) response.set_cookie( "refresh_token", refresh_token, max_age=settings.REFRESH_COOKIE_MAX_AGE, httponly=True, samesite="none", secure=False, ) return response def user_login(*, username_or_email: str, password: str) -> tuple: """ Verifies user's credentials & returns access token & refresh token. """ @dataclass(frozen=True) class UserLoginDetails: user_type: List[str] username: str user_email: str full_name: str is_verified: bool access_token: str staff: bool superuser: bool … -
Struggling with Vitess MySQL Integration: Issue
I’m working with Vitess on my server and trying to integrate it with a simple demo Django project using the Vitess MySQL databases. I’ve already set up Vitess using Docker and have successfully logged into MySQL within the Vitess container, and for the container, I used to create a subnet so the container has a separate IP. However, I’m running into an issue when trying to connect to a vitess MySQL server from outside container; even on the same server, it will not connect, showing error only -> step 1: Connect the vitess mysql server from outside container with the same server. ERROR IMAGE: enter image description here -> In that command , i use to connect host as container IP because I am trying to connect vitess MYSQL server from outside the container If I use localhost it will not connect inside container, localhost working fine inside the container but outside we must pointing the container IP then only it connect from outside. -> Step 2: Connectiong or migrating from Django application ERROR IMAGE: enter image description here -> in this django application tring to migrate the data to vitess mysql server it will show this error i tring … -
Shared hosting on Django
How to host a Django project on shared hosting? I have Python version: 3.12.8,Shared Hosting Provider: Hostinger, Web server available:Nginx and Database: SQLite.How to set up the database for Django on shared hosting and how to configure Apache or Nginx to work with Django on shared hosting. How to set up static files and media files correctly for production. -
Docker. How to fill volume at startup
I use docker-compose to run a Django project. My goal is for docker to start filled with existing data (statics, database, and all the contents of the media directory). Currently, statics are collected and distributed via volume. The database starts from a prepared dump. /media directory added to .dockerignore The question is, how to correctly fill the media volume from the media directory when you first run docker compose (that is, when the media volume is still empty)? docker-compose.yaml file: volumes: mysql_data: static: media: services: db: image: mysql:8.0 restart: always volumes: - mysql_data:/var/lib/mysql - ./database_dump.sql:/docker-entrypoint-initdb.d/dump.sql environment: - MYSQL_DATABASE=${MYSQL_DATABASE} - MYSQL_USER=${MYSQL_USER} - MYSQL_PASSWORD=${MYSQL_PASSWORD} - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} env_file: - .env backend: build: ./ depends_on: - db restart: always volumes: - static:/app/static/ - media:/app/media/ env_file: - .env nginx: build: ./gateway/ depends_on: - backend ports: - "8000:80" restart: always volumes: - static:/static/ - media:/media/ Dockerfile: FROM python:3.11 WORKDIR /app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV DJANGO_SETTINGS_MODULE='app.settings' RUN apt-get update && apt-get install -y netcat-openbsd COPY ./requirements.pip ./ RUN pip install --upgrade pip && pip install -r requirements.pip --no-cache-dir COPY . . RUN python manage.py collectstatic --no-input RUN chmod +x ./entrypoint.sh EXPOSE 8000 ENTRYPOINT ["./entrypoint.sh"] entrypoint.sh: #!/bin/sh echo "Waiting for MySQL..." while ! nc -z $MYSQL_HOST $MYSQL_PORT; … -
What's the correct way to use transaction.on_commit with Celery tasks in Django?
Approach 1: Without transaction.atomic Source: https://adamj.eu/tech/2022/08/22/use-partial-with-djangos-transaction-on-commit/ def order_created(order): order.status = 'created' order.save() transaction.on_commit( partial(send_order_email.delay, order_id=order.id) ) Approach 2: With transaction.atomic def order_created(order): with transaction.atomic(): order.status = 'created' order.save() transaction.on_commit( partial(send_order_email.delay, order_id=order.id) ) Which approach is correct and why? The save() operation makes database changes, but examples differ on whether transaction.atomic is needed. (ATOMIC_REQUESTS=False in settings) -
OSError: [Errno 24] Too many open files even after using with context manager
I've a Django application running on a server I'm using gunicorn on server this what my gunicorn service file looks like myapp.service [Unit] Description=myapp daemon Requires=myapp.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/myappApi/ ExecStart=/myappApi/venv/bin/gunicorn \ --access-logfile - \ --workers 10 \ --timeout 0 \ --bind unix:/run/myapp.sock \ myappProject.wsgi:application [Install] WantedBy=multi-user.target and this is the error I'm getting File "/myappApi/views.py", line 293, in CustomHandler Jan 23 10:48:30 myapp gunicorn[2957207]: app = CustomApp() Jan 23 10:48:30 myapp gunicorn[2957207]: File "app.py", line 22, in __init__ Jan 23 10:48:30 myapp gunicorn[2957207]: self.logger = start_logger(__file__) Jan 23 10:48:30 myapp gunicorn[2957207]: File "utils/loggerUtil.py", line 19, in start_logger Jan 23 10:48:30 myapp gunicorn[2957207]: OSError: [Errno 24] Too many open files: 'conf/config.json' above error is raised by this code from logging.handlers import RotatingFileHandler import os, logging, time, json def start_logger(__file__): os.makedirs('logs', exist_ok=True) fileName = os.path.basename(__file__) logdatetime = time.strftime("%d-%m-%Y-%I-%M") logFilename = 'logs/' + fileName[:-3] + logdatetime + '.log' logger = logging.getLogger(__file__) ''' Setting the threshold of logger to DEBUG ''' with open("conf/config.json") as f1: data = json.load(f1) # Rotating handler handler = RotatingFileHandler( logFilename, maxBytes=data['maxBytes'], backupCount=data['backupCount']) logger.addHandler(handler) return logger I've checked this answer it increases ulimit of a file which is okay but It's a temporary solution. I've noticed I'm using … -
Django: How to Represent and Query Symmetrical Relationships for a Family Tree?
I am building a family tree application in Django where I need to represent and query marriages symmetrically. Each marriage should have only one record, and the relationship should include both partners without duplicating data. Here's the relevant model structure: class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) spouses = models.ManyToManyField( 'self', through="Marriage", symmetrical=True, related_name="partners" ) class Marriage(models.Model): person1 = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="marriages_as_person1") person2 = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="marriages_as_person2") start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) I want to: Ensure both partners appear as spouses for each other symmetrically. Avoid duplicate entries for the same marriage. Efficiently query all spouses of a person. Here’s the code I’m using to query spouses: # Query spouses for a person p1 = Person.objects.create() p2 = Person.objects.create() Marriage.objects.create(person1=p1, person2=p2) p1.spouses.all() # Returns list containing p2 p2.spouses.all() # Returns empty list However, I’m facing challenges: If p1 spouses are queried, it should contain p2 and if p2 spouses are queried, it should contain p1 Both queries are not symmetrical Questions: Is my model structure correct for representing marriages symmetrically? If not, what improvements should I make? How can I efficiently query all spouses of a person in a database-optimized way while ensuring symmetry? -
Django: rest endpoint not found
I am trying to implement a rest endpoint with Django. My views.py is: from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status import json from .utils import retrieve_and_detect_faces @api_view(["POST"]) def video_analysis(request): data = json.loads(request.body) timestamp = data.get("timestamp") return JsonResponse({....}) And in urls.py: from django.urls import path from .views import video_analysis urlpatterns = [ path('video_analysis/', video_analysis, name = 'video_analysis') ] But when I try to call this endpoint, I get error: Not Found: /video_analysis [24/Jan/2025 07:37:26] "POST /video_analysis?timestamp=1234567 HTTP/1.1" 404 2262 What configuration am I missing in my program? -
AllAuth.url is not working and not showing path sugestions
Setting.py: INSTALLED_APPS = [ 'channels', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', "allauth.account.middleware.AccountMiddleware", 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] File: url.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] Like, I just followed the quickstart of all auth, and I've done this once before with a tutorial, but this time something went wrong because when I search for : localhost:8000/accounts/ it says the path doesn't exists, instead of giving me suggestions of follow up. And when I go localhost:8000/ it does suggest admin/, accounts/ -
BadRequest can't return JSON?
I am trying to return a JSON object along with a 400 error code. This correctly returns the object (e.g. {"email": ["A user with that email address already exists."]}: return HttpResponse(json.dumps(dict(form.errors.items()))) Whereas these all just returns an unreadable (by javascript) object ([object Object]): return BadRequest(json.dumps(dict(form.errors.items()))) return HttpResponseBadRequest(json.dumps(dict(form.errors.items()))) return BadRequest(json.dumps(dict(form.errors.items())), content_type='application/json') I've tried several other methods of sending an error code but the results were the same. How do I get the readable object along with a 400 Bad Request error code?