Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache 2.4 mod_wsgi windows server multiple hosting - not running more than two Django projects
httpd.conf file ServerName 172.31.4.38 Listen 8001 Listen 8002 Listen 8003 LoadFile "C:/Users/Administrator/AppData/Local/Programs/Python/Python311/python311.dll" LoadModule wsgi_module "C:/Users/Administrator/AppData/Local/Programs/Python/Python311/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp311-win_amd64.pyd" WSGIPythonHome "C:/Users/Administrator/AppData/Local/Programs/Python/Python311" WSGIPythonPath "D:/adhocvenv/Lib/site-packages" **virtual host configuration ** <VirtualHost *:8001> ServerName 172.31.4.38 WSGIScriptAlias / "D:\adhocvenv\adhocpayroll\adhocpayroll\wsgi.py" application-group=site1 <Directory "D:\adhocvenv\adhocpayroll"> Require all granted </Directory> </VirtualHost> <VirtualHost *:8002> ServerName 172.31.4.38 #DocumentRoot "D:/StoreManagementSystem" WSGIScriptAlias / "D:/StoreManagementSystem/StoreManagementSystem/wsgi.py" application-group=site2 <Directory "D:/StoreManagementSystem"> Require all granted </Directory> </VirtualHost> <VirtualHost *:8003> ServerName 172.31.4.38 DocumentRoot "D:/HealthCenter" WSGIScriptAlias / "D:/HealthCenter/HealthCenter/wsgi.py" application-group=site3 <Directory "D:/HealthCenter"> Require all granted </Directory> </VirtualHost> ** First two projects are running successfully. For the third projects its showing internal server misconfiguration. What is the wrong with the above configurations? Why misconfiguration? I've verified that each site works individually.** -
Django 4.2.7 & django-allauth 0.58.2 "next" parameter issue
I am trying to redirect my user after login to page he refered, using login_required decorator. If I do not provide {{ redirect_field_name }} in login template it does not work at all (redirects to LOGIN_REDIRECT_URL, even "next" parameter in url exists). But when I provide {{ redirect_field_name }} it firstly redirects to "/accounts/login/next" (with 404 error) and when I press back button it goes to desired page. Could somebody help me to solve this issue? -
how to use redis in cpanel for python (django)
I have used Redis for sending email in localhost for change password but now i want use it for send email in server in Cpanel but when I use it error comes like "connection refuse" please any one help me I am trying to solve it since two days the solution should be a to z step by step -
Python Django ConnectionRefusedError: [Errno 111] Connection refused
When using SMTP from Brevo, it works fine on localhost. However, after deploying the project to PythonAnywhere, I encountered a connection refusal error. EMAIL_HOST = 'smtp-relay.brevo.com' EMAIL_PORT = '587' EMAIL_HOST_USER = env.str('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env.str('EMAIL_HOST_PASSWORD') I found an article on Brevo (article) how to check port availability. After following the steps, I attempted to connect by entering "telnet smtp-relay.brevo.com 587" but received an error message stating "Trying 1.179.118.1... telnet: Unable to connect to remote host: Connection refused" -
Not able to update Django model with HTMX button click
I am using Django, Tailwind CSS, and HTMX. I am trying to update my Django model (Item) which starts as None to use a dropdown select to change the color then use a button to Save and update the Item.color on the Django model. The HTML shows up, and I am able to make the request (the url shows up: "https://localhost/detail-view/my-item-2/?id=my-item-2&color=YELLOW"), but the model is not being updated and I can't get the JsonResponses to show up. I'm not sure if there is something wrong with how I am using my POST request? Can anyone help? models.py class Item(models.Model): id = models.AutoField(primary_key=True) color = models.CharField( "Color", blank=True, null=True, choices=MyConstants.Color.choices, ) constants.py class Color(models.TextChoices): RED = "RED" YELLOW = "YELLOW" GREEN = "GREEN" views.py @require_POST def update_color(request): if request.method == "POST": new_status = request.POST.get("color") item_id = request.POST.get("item_id") item = Items.objects.filter(id=item_id) item.update_or_create( color=new_color ) item.save() return JsonResponse({"message": "Color updated successfully"}) return JsonResponse({"message": "Not a post request: failed to update color"}) color_picker.html {% block main_content %} <div class="p-5"> <div class="mb-6"> <h1 class="text-2xl">Overview</h1> <p class="text-sm">{{ item.id }}</p> </div> <div class="pb-4"> <label for="color" class="text-lg ">Color</label> <form hx-post="{% url "update_color" %}" hx-swap="outerHTML" > <input type="hidden" name="item_id" value="{{ item.id }}"/> <div class="flex"> <select id="color" name="color" class="w-1/4 p-2" … -
Installed django in virtual env, but I can't import
I installed Django in virtual env. But I got error. raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I use python 3.12.0 and tried reinstall all venv and packages, but got same error. After installing django in virtual environment, still can't import module is not helpful. -
Django Form: Filter and display options based on objects created by user in a form
The current problem is that my form shows the logged-in user all 'decks' ever created. The form should only show 'decks' that the logged-in user created. I can filter the decks from the given user, but I can't get that information passed as the only options a user can select from. models.py class Profile(models.Model): profile_pic = models.ImageField(null=True, blank=True, default='Default.png', upload_to='images/') user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.user) class Deck(models.Model): deck = models.CharField(max_length=150) is_cedh = models.BooleanField(default=False) user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) def __str__(self): return self.deck class Game(models.Model): deck = models.ForeignKey(Deck, on_delete=models.CASCADE, null=True) wincon = models.ForeignKey(Wincon, on_delete=models.CASCADE, null=True, blank=True) tournament = models.BooleanField(default=False) num_players = models.IntegerField(choices=NUM_PLAYERS_CHOICE, default=4) start_pos = models.CharField(max_length=20, choices=START_POS_CHOICE, default=1) mull = models.CharField(max_length=20, choices=MULL_CHOICE, default='1st 7') outcome = models.CharField(max_length=10, choices=OUTCOME_CHOICE, default='Win') medium = models.CharField(max_length=10, choices=MEDIUM_CHOICE, default='Paper') date = models.DateField(auto_now=True) time = models.TimeField(auto_now=True) views.py def game_tracker(request): user_decks = Deck.objects.filter(user=request.user) if request.method == "POST": form = GameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/track') else: form = GameForm() context = {'form': form, } return render(request, 'gametracker_app/gametracker.html', context=context) forms.py class GameForm(forms.ModelForm): class Meta: model = Game exclude = {'date', 'time', } labels = { 'deck': 'What deck', 'num_players': '# of Players', 'start_pos': 'Starting position', 'mull': 'Starting hand', 'outcome': 'Outcome', 'wincon': 'Wincon', 'medium': 'Paper … -
Updating html for specific model instance Django
I have a Django template that generates a HTML 'card-like' element for each model instance. Each instance (ie 'post') have a button, when on click, I would like to update a value within that SAME instance. I have been able to do this within the database, but am struggling with updating the HTML to match. Currently, my solution is updating ALL instances/posts. However, I only want to update it on the instance that had the button click. Does this make sense? Let me know if it doesn't. I will attach my code below along with an image demonstration. I did try passing through the event ID and making sure they align up for both the button and paragraph tag, but this seemed to not work. JS: function signUp(user, event, btn, eventID) { var csrftoken = Cookies.get("csrftoken"); var user_id = user var event_id = event attendance_count = document.querySelectorAll("#attendance"); if (btn.classList.contains("event-btn")){ request_info = "register"; } else if (btn.classList.contains("signUpBtnActive")){ request_info = "unregister"; } $.ajax({ type: "POST", url: "/event/update-attendance/", data: { user_id: user_id, event_id: event_id, request_info: request_info, "csrfmiddlewaretoken": csrftoken }, }).done(function(response){ if (attendance_count){ attendance_count.forEach(element => { event_id = element.getAttribute("event-instance"); if (event_id == eventID){ element.innerHTML = response; } }) } }); } My view: def … -
Django app working locally anyhow when I push it to Heroke it will display a 500 error (H10)
I started my Django app with the sqlite default data base and later on I proceeded the steps (shown below) since I wanted to host it in Pythonanywhere since it was a cheaper alternative (it did not work), I sadly could not successfully deploy to Heroku as well. My project Repository looks like this: RECIPE-APP/ |-include/ |-Lib/ |-Scripts/ |-src/ |-media/recipes/ |-recipe_app/ |-settings.py |-wsgi.py |-recipes/ |-.env |-data.json |-db.sqlite3 |-manage.py |-.gitatributes |-.gitignore |-Procfile |-pyvenv.cfg |-requirements.txt I have a .env set up containing all keys for the DATABASES, in which case I copied all the required keys to heroku config vars. I reviewed the Procfile and it should be ok. Procfile: web: gunicorn src.recipe_app.wsgi --log-file - settings.py: """ Django settings for recipe_app project. Generated by 'django-admin startproject' using Django 4.2.6. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path import os import dotenv from decouple import config # import environ # from dotenv import load_dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # initialize environment variable # env = environ.Env() … -
Docker Deployment Issue: "unable to set PTHREAD_PRIO_INHERIT"
I am trying to deploy my Django application through Docker. When I build it in the terminal (docker-compose -f docker-compose-deploy.yml up --build), everything is successful until I get this error: dockerdeploymenttest-app-1 | !!! no internal routing support, rebuild with pcre support !!! dockerdeploymenttest-app-1 | your memory page size is 4096 bytes dockerdeploymenttest-app-1 | detected max file descriptor number: 1048576 dockerdeploymenttest-app-1 | lock engine: pthread robust mutexes dockerdeploymenttest-app-1 | unable to set PTHREAD_PRIO_INHERIT dockerdeploymenttest-app-1 exited with code 1 This is stopping my project from being deployed, and I can't seem to figure out why. Why is this happening, and how can I fix it? Dockerfile: FROM --platform=linux/amd64 python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install -r requirements.txt RUN apk del .tmp RUN mkdir /TeenSocial COPY ./TeenSocial /TeenSocial WORKDIR /TeenSocial COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] docker-compose.yml version: '3.8' services: app: build: context: . ports: - "8000:8000" volumes: - ./TeenSocial:/TeenSocial command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 docker-compose-deploy.yml version: '3.8' services: … -
Why my RDS instance is not connecting with my Django project?
I'm trying to connect my Django Project with a RDS instance with Postgre engine It's a free tier option The instance is running normally with no problems I've set my Inbound Rule to allow Postgre connection with my IP DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'angtradingdatabase', 'USER': 'vitor', 'PASSWORD': 'xxxxxx', 'HOST': 'angtradingdatabase.xxxxxxx.us-east-2.rds.amazonaws.com', 'PORT': '5432', } } But I'm receiving this error when I try to run the 'python manage.py runserver' code django.db.utils.OperationalError: connection to server at "angtradingdatabase.cbe1o6n4gvvs.us-east-2.rds.amazonaws.com" (18.117.34.123), port 5432 failed: FATAL: database "angtradingdatabase" does not exist The name of my database is angtradingdatabase as you can see in the picture, what is causing this problem?? Create new databases -
I can't run pip install, it's giving this error in djnago's python, I want to run "pip install -r requirements.txt "
(venv) PS C:\Users\windows-10\OneDrive\Área de Trabalho\template-main> pip install -r requirements.txt Collecting absl-py==2.0.0 (from -r requirements.txt (line 1)) Using cached absl_py-2.0.0-py3-none-any.whl.metadata (2.3 kB) Collecting astunparse==1.6.3 (from -r requirements.txt (line 2)) Using cached astunparse-1.6.3-py2.py3-none-any.whl (12 kB) Collecting cachetools==5.3.2 (from -r requirements.txt (line 3)) Using cached cachetools-5.3.2-py3-none-any.whl.metadata (5.2 kB) Collecting certifi==2023.7.22 (from -r requirements.txt (line 4)) Using cached certifi-2023.7.22-py3-none-any.whl.metadata (2.2 kB) Collecting charset-normalizer==3.3.1 (from -r requirements.txt (line 5)) Using cached charset_normalizer-3.3.1-cp312-cp312-win_amd64.whl.metadata (33 kB) Collecting flatbuffers==23.5.26 (from -r requirements.txt (line 6)) Using cached flatbuffers-23.5.26-py2.py3-none-any.whl.metadata (850 bytes) Collecting gast==0.5.4 (from -r requirements.txt (line 7)) Using cached gast-0.5.4-py3-none-any.whl (19 kB) Collecting google-auth==2.23.3 (from -r requirements.txt (line 8)) Using cached google_auth-2.23.3-py2.py3-none-any.whl.metadata (4.2 kB) Collecting google-auth-oauthlib==1.0.0 (from -r requirements.txt (line 9)) Using cached google_auth_oauthlib-1.0.0-py2.py3-none-any.whl (18 kB) Collecting google-pasta==0.2.0 (from -r requirements.txt (line 10)) Using cached google_pasta-0.2.0-py3-none-any.whl (57 kB) Collecting grpcio==1.59.0 (from -r requirements.txt (line 11)) Using cached grpcio-1.59.0-cp312-cp312-win_amd64.whl.metadata (4.2 kB) Collecting h5py==3.10.0 (from -r requirements.txt (line 12)) Using cached h5py-3.10.0-cp312-cp312-win_amd64.whl.metadata (2.5 kB) Collecting idna==3.4 (from -r requirements.txt (line 13)) Using cached idna-3.4-py3-none-any.whl (61 kB) Collecting keras==2.14.0 (from -r requirements.txt (line 14)) Using cached keras-2.14.0-py3-none-any.whl.metadata (2.4 kB) Collecting libclang==16.0.6 (from -r requirements.txt (line 15)) Using cached libclang-16.0.6-py2.py3-none-win_amd64.whl.metadata (5.3 kB) Collecting Markdown==3.5 (from -r requirements.txt (line 16)) Using cached Markdown-3.5-py3-none-any.whl.metadata (7.1 … -
Django datetime loaded incorrectly from database
I have a Django application for viewing sensor observations. This is my observation model: class Observation(models.Model): timestamp = models.DateTimeField() sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE) value = models.DecimalField(max_digits=6, decimal_places=3) In one of my views, I want to use the timestamp of the latest observation: latest_observation = Observation.objects.order_by('-timestamp').values('timestamp').first() context['latest_data_timestamp'] = latest_observation['timestamp'] if latest_observation else None The timestamp is stored correctly in the database (UTC). However, when running my view, the timestamp is changed to the timezone set in settings.py, but the tzinfo is still 'UTC'. Timezone support is enabled in settings.py: TIME_ZONE = 'Europe/Amsterdam' USE_TZ = True For example, a timestamp stored in the database as 2023-11-22 18:00:00+00:00 is loaded as 2023-11-22 19:00:00+00:00, but if I understand it correctly, it should be 2023-11-22 19:00:00+01:00. (Ignoring daylight saving time, 'Europe/Amsterdam' is UTC+1) What am I doing wrong, and how do I fix this? I tried using astimezone to set the timezone correctly, but that doesn't work. I could also simply replace the tzinfo, but it feels like a hacky solution. There's probably a better way... -
Django Gunicorn Nginx *254 connect() to unix:/run/gunicorn.sock failed (111: Unknown error)
I am attempting to deploy a Django application on a Ubuntu 22.04 EC2 instance to the web following this tutorial: https://medium.com/@codewithmuh/host-django-application-using-gunicorn-nginx-in-production-on-aws-ubuntu-server-4b1551e13c66 I cannot access the contents of my application/project when I go through these steps, search my Public IPv4 address (even when I have it included in my list of allowed hosts). My folder path is /home/ubuntu/portfolio/portfolio and I'm using miniconda as my venv My configs are: Settings.py DEBUG = False ALLOWED_HOSTS = ['18.189.143.92'] # Application definition INSTALLED_APPS = [ "home.apps.HomeConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "whitenoise.runserver_nostatic", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django_extensions", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] sites-enabled/sites-available server { listen 80 default_server; server_name _; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/portfolio/portfolio; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/portfolio/portfolio ExecStart=/home/ubuntu/portfolio/portfolio/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ --timeout 60 \ portfolio.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target The error I'm getting: 2023/11/22 19:31:08 [error] 17524#17524: *10 connect() to unix:/run/gunicorn.sock failed (111: Unknown error) while connecting to upstream, client: 130.211.54.158, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: … -
point to static files from js loop
in my html i have this <img src="{% static 'fps_assets/health_hud.png'%}" alt="health image" style="float:left;"> the above html works for finding C:\Users\..........\static\fps_assets\health_hud.png but the following js code does not find something similar js var staticBaseUrl1 = "{% static 'fps_assets/"; var staticBaseUrl2 = "' %}"; function load_door_sprites(door_images_list){ var door_images_list_path = []; for (let i = 1; i <= 13; i++) { if (i==1){door_images_list_path.push("door_alpha.png");} else{door_images_list_path.push("door"+i.toString()+"_alpha.png");} } door_images_list_path.forEach(imageURL => { const image = new Image(); console.log(staticBaseUrl1 + imageURL+staticBaseUrl2); image.src = staticBaseUrl1 + imageURL+staticBaseUrl2; image.onload = imageLoaded; door_images_list.push(image); }); return door_images_list } i get this printed from the console.log.... {% static 'fps_assets/door_alpha.png' %} {% static 'fps_assets/door2_alpha.png' %} and this error GET http://localhost:8000/%7B%%20static%20'fps_assets/door_alpha.png'%20%%7D 404 (Not Found) GET http://localhost:8000/%7B%%20static%20'fps_assets/door2_alpha.png'%20%%7D 404 (Not Found) and the full path for the file i wanted it find C:\Users\............\static\fps_assets\door_alpha.png -
Get the latest index of each author in a message list - Python - Django
I have the following message model in Django: class Message(models.Model): appointment = models.ForeignKey(Appointment, ...) author = models.ForeignKey(User, ...) role = models.CharField(max_length=50, choices=Role.choices, ...) message = models.TextField(null=False) created_at = models.DateTimeField(auto_now_add=True) Suppose I retrieve a query set for a given appointment id: Message.objects.filter(appointment_id=id) which, for example, could be as follows: queryset = [Message_A, Message_A, Message_B, Message_A] where Message_A is from author A and Message_B is from author Β. You can distinguish the authors based on their field role, which takes values A and B. Also, the messages are sorted chronologically based on the created_at field, from oldest to newest. It is required to find the index of the last record for each author in an efficient way; in our example, for author A, it would be 3, and for author B, it would be 2. The index of one author will be the size of the queryset - 1. How do we find the index of the other author as efficiently as possible? -
My scraper search app is returning 400 Bad Request and I am unsure why
I'm trying to create a search engine which returns keyword results from findaphd.com. This is my Python code and I am unsure what I'm doing wrong. I'm quite new to coding so apologies if this is a dumb question. import requests from bs4 import BeautifulSoup from django.shortcuts import render def results(request): if request.method == "POST": query = request.POST.get('search') if query == "": return render(request, 'engine/home.html') else: results = [] page = requests.get('https://www.findaphd.com/phds/phd-research-projects/united-kingdom/non-eu-students/?g3w9E00&Sort=T&PG=1').text soup = BeautifulSoup(page, 'html.parser') listings = soup.find_all(class_="phd-result") for content in listings: title = content.find(class_='phd-result__title').text.strip() # Update class names description = content.find(class_='phd-result__description').text.strip() link = content.find('a', class_='phd-result__description--read-more')['href'] # Extract the href attribute results.append((title, description, link)) context = { 'results': results } return render(request, 'engine/results.html', context) else: return render(request, 'engine/home.html')` ` I was expecting to have a search results page returned but instead I got 400 Bad Request. -
PostgreSQL Performance Issues in Docker After Migrating Diango 2.0.1 Application to New Server
I'm experiencing issues after migrating my Django application from an old server to a new one, with the application now running in Docker. Below is my docker-compose.yml: version: '3.8' services: way_db: image: postgres:10 restart: always volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=ways - POSTGRES_PASSWORD=******** - POSTGRES_DB=ways_db - PGPORT=5432 railway_redis: image: "redis:alpine" ports: - "6379:6379" railway_web: build: . command: gunicorn -w 4 -b 0.0.0.0:8888 priv_project.wsgi:application restart: always volumes: - .:/app ports: - "8888:8888" depends_on: - railway_db - railway_redis environment: - DATABASE_HOST=railway_db - DATABASE_NAME=railways_db - DATABASE_USER=railways - DATABASE_PASSWORD=********* - DJANGO_SETTINGS_MODULE=priv_project.settings.production railway_celery_worker: build: . command: celery -A priv_project worker --loglevel=info volumes: - .:/app depends_on: - railway_db - railway_redis environment: - DJANGO_SETTINGS_MODULE=priv_project.settings.production - CELERY_BROKER_URL=redis://railway_redis:6379/0 - CELERY_RESULT_BACKEND=redis://railway_redis:6379/0 railway_celery_beat: build: . command: /bin/sh -c "rm -f /app/celerybeat.pid && celery -A priv_project beat --loglevel=info --scheduler django_celery_beat.schedulers:DatabaseScheduler" volumes: - .:/app depends_on: - railway_db - railway_redis environment: - DJANGO_SETTINGS_MODULE=priv_project.settings.production - CELERY_BROKER_URL=redis://railway_redis:6379/0 - CELERY_RESULT_BACKEND=redis://railway_redis:6379/0 - CELERY_BEAT_PID_FILE=/app/celerybeat.pid railway_backup_app: build: ./backups_railway environment: - TZ=Asia/Almaty - BACKUP_TIME=23:00 # backup time in 24h format - BACKUP_RETENTION_DAYS=30 # how many days to keep backups - HOME=/app - LOG_BACKUPS_COUNT=30 - LOG_BACKUPS_SIZE_BYTES=2000000 volumes: - ./backups_railway:/app volumes: postgres_data: I'm facing periodic database performance issues, such as: app-master-appway_db-1 | 2023-11-22 16:49:00.354 UTC [35388] ERROR: canceling statement due to statement timeout … -
formatting error in a field models.DateField()
I have a model in the models.py file of my django project, where a date field does not respect the format in the admin, where it appears as if it were a charField. from django.db import models class registro(models.Model): fechaNacimiento = models.DateField() -
Why does my modal not open in my django project?
I try to create full CRUD for my commenting, but as soon as I added editing and deletion. It stopped wanting to open upon pressing the add comment button. The modal doesn't open. Its a newsbulletinboard, it has separate articles that is fetched by API. It is parsed and rendered unto the landingpage. Each article has the oppertunity for each user to comment. {% extends "base.html" %} {% block content %} <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-10 mt-3"> <div class="row"> {% for news_article in news_article_list %} <div class="col-12"> <div class="card mb-4" style="width: 100%; margin: auto;"> <div class="card-body"> <h2 class="card-title">{{ news_article.title }}</h2> <p class="card-text">{{ news_article.content|linebreaks }}</p> <p class="card-text text-muted h6">{{ news_article.created_on }}</p> <hr /> <div class="row"> <div class="col-12"> <!-- Stored comments according to article-id --> <div class="comments-section"> {% for comment in news_article.comments.all %} <div class="comment"> <strong>{{ comment.name }}</strong> <p>{{ comment.comment_content }}</p> {% if user.is_authenticated %} <div class="justify-content-center"> <button id="edit-comment-btn{{ news_article.id }}" class="btn btn-secondary btn-dark open-comment-form" data-action="edit" data-comment-id="{{ comment.id }}">Edit</button> <button id="delete-comment-btn{{ news_article.id }}" class="btn btn-secondary btn-dark open-comment-form" data-article-id="{{ news_article.id }}">Delete</button> {% endif %} </div> <hr> <small class="text-muted">{{ comment.created_on }}</small> </div> {% endfor %} </div> {% if user.is_authenticated %} <button id="open-comment-form-{{ news_article.id }}" class="btn btn-secondary btn-dark open-comment-form" data-article-id="{{ news_article.id }}">Add a … -
TemplateSyntaxError Exception Value
TemplateSyntaxError at / Invalid block tag on line 41: 'url_for', expected 'endblock'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 41: 'url_for', expected 'endblock'. Did you forget to register or load this tag? Exception Location: C:\Users\Hamprey Aganyo Ndemo\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py, line 558, in invalid_block_tag Raised during: trying.views.index Python Executable: C:\Users\Hamprey Aganyo Ndemo\PycharmProject\trying\venv\Scripts\python.exe Python Version: 3.12.0 Python Path: ['C:\\Users\\Hamprey Aganyo Ndemo\\PycharmProject\\trying', 'C:\\Users\\Hamprey Aganyo ' 'Ndemo\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\Hamprey Aganyo ' 'Ndemo\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\Hamprey Aganyo ' 'Ndemo\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\Hamprey Aganyo Ndemo\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\Hamprey Aganyo Ndemo\\PycharmProject\\trying\\venv', 'C:\\Users\\Hamprey Aganyo ' 'Ndemo\\PycharmProject\\trying\\venv\\Lib\\site-packages', 'C:\\Users\\Hamprey Aganyo ' 'Ndemo\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages'] Server time: Wed, 22 Nov 2023 15:24:30 +0000 Error during template rendering In template C:\Users\Hamprey Aganyo Ndemo\PycharmProject\trying\templates\index.html, error at line 41 -
How to integrate Asterisk AMI with our custom CRM to make auto-calls to customers whenever there's a new number
we developed a custom CRM where we collect user phone number and other details. Recently, our company started using IP telephony system, more specifically they are using Asterisk AMI and we wanted to integrate it with our CRM. The point of it is now our call centre is exporting the list of customers from CRM and manually calling each of them(sometimes it takes days after to call a customer in which point they already change their mind), but we want to automate it and call them after we get the customer's number in the order of LIFO. Unfortunately, I couldn't find any helpful information from the company who installed IP telephony system and other places. Can anyone help with it please? We tried to contact the people who set up the IP telephony company, they provided some materials but they are useless. And checked internet official asterisk site and other places, but we couldn't figure out how to implement it -
why I have target Error when i did HTMX inline editing?
I'm doing a Django project and want to use HTMX to achieve inline edit, I can click the title to change the text, but once I click the save button, it shows targetError. I just checked that I used the correct reference name. I couldn't figure out where is my mistake. view.py def editProject(request,pk): project=Project.objects.get(id=pk) print(project.name) print(request.method) if request.method == 'POST': print(request.method) project.name=request.POST.get('name','') print(f'project name: {project.name}') project.save() return render(request,'tool/{project.id}',{'project':project}) return render(request,'tool/partials/editProject.html',{'project':project}) ProjectDetail.html <h1 id="projectName" hx-get="{% url 'tool:editProject' pk=project.pk%}" hx-target="this" hx-swap="outerHTML"> {{project.name}}</h1> editProject.html <form hx-post="{% url 'tool:editProject' pk=project.pk%}" hx-target="closest h1" <!-- I also tried use #projectName, still not working --> hx-swap="outerHTML" hx-headers="{ 'X-CSRFToken': '{{ csrf_token }}' }" class="flex" > <input type="text" name="name" value="{{project.name}}" autofocus> <button class="text-sky-600 hover:text-sky-900"> Save</button> </form> -
Making Downloaded Files a Parameter for Subsequent Functions in Django, Celery, and Digital Ocean Spaces Integration
How can I utilize Django with Celery to handle a scenario where a function downloads a file from Digital Ocean Spaces, and once the download is complete, I want to pass the downloaded file as a parameter to the StorageContext function? Something like, whenever it has the file, then proceed. Here is what i've tried: @celery_app.task() def download_file_from_digital_ocean(folder_key, local_folder): try: session = boto3.session.Session() client = session.client( "s3", region_name=settings.AWS_S3_REGION_NAME, endpoint_url=settings.AWS_S3_ENDPOINT_URL, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) object_list = [ f"test/{folder_key}/docstore.json", f"test/{folder_key}/graph_store.json", f"test/{folder_key}/index_store.json", f"test/{folder_key}/vector_store.json", ] subfolder_path = os.path.join(local_folder, folder_key) os.makedirs(subfolder_path, exist_ok=True) for file_path in object_list: file_name = file_path.split("/")[-1] local_file_path = os.path.join(subfolder_path, file_name) client.download_file( Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=file_path, Filename=local_file_path, ) return True except Exception as e: print(f"Connection error: {e}") return False @celery_app.task() def llma_index_new_update(url, url_text, question): try: API_KEY = settings.APP_OPEN_AI_API_KEY url_id = url["id"] openai.api_key = API_KEY folder_key = f"storage{url_id}" local_folder = "local_test/" download_task = download_file_from_digital_ocean.delay(folder_key, local_folder) storage_context = StorageContext.from_defaults( persist_dir="local_test/storage" + str(url["id"]) ) index = load_index_from_storage(storage_context, index_id=url["url"]) query_engine = index.as_query_engine(response_mode="tree_summarize") response = query_engine.query(question) data = { "url": url_instance, "url_asked": url_text, "question": question, "response": response.response, } return_data = { "url_asked": url_text, "question": question, "response": response.response, } save_db = save_to_db_question(data) return return_data except Exception as e: print(e) any idea on how can I implement this? -
Come effettuare una verifica dell'input dell'utente con più campi di un modello django?
Premetto che sono neofita nel mondo della programmazione e da agosto di quest'anno ho iniziato a studiare da autodidatta Python e successivamente Django. Sto cercando di implementare una view per la cui se sei autenticato come utente django e se inserisci una chiave e un numero di telefono che corrispondono con quello registrato nel database allora hai accesso ad una risorsa url specifica. Gli step sarebbero i seguenti: In Homepage c'è un button che se cliccato reindirizza alla view access_to_events_by_secret che istanzia il form con i due campi da compilare. Quindi l'utente inserisce i dati e a quel punto vengono verificati i dati inseriti e se corrispondono al numero di telefono e alla chiave presenti nel database allora si viene reindirizzati ad uno specifico URL. Ecco il codice: Models.py from django.db import models from .utils import generate_code # Create your models here. class Secret(models.Model): name = models.CharField(max_length=50) key = models.CharField(max_length=15, blank=True, unique=True) phone_number = models.CharField(max_length=13) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def save(self, *args, **kwargs): if self.key == "": self.key = generate_code() return super().save(*args, **kwargs) Utils.py import uuid def generate_code(): code = uuid.uuid4() code_mod = str(code).replace('-', '').upper()[:15] return code_mod Forms.py from django import forms from .models …