Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
(WAGTAIL) How to customize the FileField field?
I have a FileField field in my Wagtail model. In the administrative area, I intend to offer a single download button exclusively for this field. The rationale behind this decision is that the data will be pre-populated from the backend. class ReportCSV(models.Model): file = models.FileField( null=True, blank=True, verbose_name=_("File"), upload_to=csv_directory_path, ) -
re render a django view with change in context after POST request
I am trying to change content of a table by applying filters in a django template but I am unable to re render the same page again with change in context. I don't want to use javascript or class based views so could you please suggest a way to do it in django function based view. Below is sample code def Endtoendtrackerview(request,*args,**kwargs): def executefunction(orderobj,baseobj): 'somecode which returns a context dictionary return context if request.method = POST: 'some code orderobj = OrderModel.objects.filter(status = True) baseobj = BaseModel.objects.filter(process = process) context = executefunction(orderobj,baseobj) return render(request, "app/end_to_end_tracker.html",context) orderobj = OrderModel.objects.all() baseobj = BaseModel.objects.all() context = executefunction(orderobj,baseobj) return render(request, "app/end_to_end_tracker.html",context) -
Items not getting store in databse after submit
I am building this website in Django where I am storing locations as "items" inside a databse. Users are allowed to enter a detailed view of each location, and then press a "Rate" button which should open a form that lets them enter a rating. Later I want to display on each location an average of the users s ratings. I Stored the rating of users with respect to an object in a database called "Ratings". However, when I submit, items don t get stored in the "ratings". This is the views file: `from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from .models import Item from .forms import RateItemForm # Create your views here. def detail(request, pk): item = get_object_or_404(Item, pk = pk) related_items = Item.objects.filter(category = item.category, is_sold = False).exclude(pk=pk).order_by('-price')[0:3] items = Item.objects.filter(is_sold = False).order_by('-price')[0:6] highest_rated_item = items.first() return render(request, 'item/detail.html', { 'item': item, 'related_items' : related_items, 'highest_rated_item' : highest_rated_item }) @login_required(login_url='/login/') def rate(request, pk): item = get_object_or_404(Item, pk = pk) if request.method == "POST": form = RateItemForm(request.POST) if form.is_valid(): rating = form.save(commit=False) rating.user = request.user rating.item = item rating.save() return redirect('item:detail', pk = rating.id) else: print(form.errors) else: form = RateItemForm() return render(request, 'item/rate.html', { 'item': item, … -
Django sign up using OTP send to telegram
Iam using Django User model with extra phone number phone class CreateUserForm(UserCreationForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = forms.CharField(validators=[phone_regex], max_length=17) class Meta: model = UserProfile fields = ['username', 'email', 'phone', 'password1', 'password2'] and after, user add all the input need and press sign up button from template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div style=" position:absolute; top:62%; left:50%; padding:10px; -ms-transform: translateX(-50%) translateY(-50%); -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"> <form method="post"> {% csrf_token %}{{form|crispy}} <p>Have an account? Login <a href="/login">Here</a>!</p> <button type="submit" class="btn btn-success">Register</button> </form> </div> {% endblock %} and then i want to change user to verify code page that generate code and send that code to user through telegram. But because telegram need chat id so the bot can send message to user, i can't figure out how to get that id when user press get code in verify_code template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div style=" position:absolute; top:50%; left:50%; padding:10px; -ms-transform: translateX(-50%) translateY(-50%); -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"> <h1>Verify Code</h1> <a href="https://t.me/AccountToken_bot" target="_blank"> Get Code </a> <p>Enter the 6-digit code you received on Telegram:</p> <form … -
Override Django Admin Save Model
I want to override Django form save method to be able to create multiple objects at once. I have an AvailableHours model : class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,null=True, blank=True,on_delete=models.CASCADE,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True) free_hours_to = models.IntegerField(null=True, blank=True,) status = models.BooleanField(null=True,default=True,) and I have a ModelForm for this class : class TimeGenerator(forms.ModelForm): class Meta: model = AvailableHours fields = ['free_date','free_hours_from','free_hours_to','status'] def save(self, commit=True): base_item = super().save(commit=False) frm = self.cleaned_data['free_hours_from'] to = self.cleaned_data['free_hours_to'] items = [ AvailableHours( free_date=base_item.free_date, status=base_item.status, free_hours_from=hour, free_hours_to=hour + 1, ) for hour in range(frm, to) ] if commit: AvailableHours.objects.bulk_create(items) return items I want to create multiple AvailableHours object like this: if the form is set free_hours_from = 13 and free_hours_to=16 so the save method creates 13-14 , 14-15, 15-16 I achieved this by overriding my ModelForm but now I want to override Admin Save model to do this from Django Admin. I tried by doing it like this in admin.py class AvailableHoursAdmin(admin.ModelAdmin): def save_model(self, commit=True): base_item = super().save(commit=False) frm = self.cleaned_data['free_hours_from'] to = self.cleaned_data['free_hours_to'] items = [ AvailableHours( free_date=base_item.free_date, status=base_item.status, free_hours_from=hour, free_hours_to=hour + 1, ) for hour in range(frm, to) ] if commit: AvailableHours.objects.bulk_create(items) return items admin.site.register(AvailableHours,AvailableHoursAdmin) but no luck. anyone has a solution for this ? -
Celery Task ECS Termination Issue - Need Help Updating Decorator for Handling ProtectionEnabled State Changes
Explanation: I have a Django application where I am running multiple Celery tasks on AWS Elastic Container Service (ECS), using SQS as the broker. I am encountering an issue where the Celery tasks are being started in an existing ECS task once the previous one is completed. The issue arises because my decorator changes the status of ProtectionEnabled from true to false, and after a couple of seconds, the ECS task is terminated. The newly started task then fails to work. Below is the command I am running to start celery task. celery -A myapp_settings.celery worker --concurrency=1 l info -Q sqs-celery I am using alerts on CloudWatch to check messages in broker and terminate those ECS tasks that are completed. The problem is that celery is starting task in existing ECS task once the previous one was completed. It would not be a problem but my decorator changes the status of ProtectionEnabled from true to false and after 20 seconds ECS task is terminated and newly started task is not working anymore. Question: I am considering updating my decorator to change back the ProtectionEnabled value from false to true if a new Celery task starts, but I am unsure how … -
Using stage_block API to upload file chunk is so slow when executing under Uwsgi request in Django
I am using python 2.7.18 with azure-storage-blob==12.3.2 and Django to implement file upload with small chunk, when calling stage_block API in interactive mode directly each chunk request takes less than a second. While under Uwsgi request , it was so slow and each chunk data need almost 90 seconds to complete. What are the possible reasons? # directly calling from azure.storage.blob import BlobClient import base64 import os container = "test" blob_name = "test" blob = BlobClient(account_url=******, container_name=container, blob_name=blob_name) chunk_size = chunk*1024*1024 block_ids = [] index = 0 with open(file_path, 'rb') as f: while True: data = f.read(chunk_size) if data: length = len(data) block_id = base64.encodestring(str(index)).strip() blob.stage_block(block_id, data) index += 1 else: break resp = blob.commit_block_list(block_ids) # Django request,uwsigi wrapped from azure.storage.blob import ContainerClient container = ContainerClient(account_url=********, container_name="test") def process_chunk(request): import base64 id = request.GET['id'] idx = request.GET['idx'] data = base64.b64decode(request.POST['data']) blob = container.get_blob_client(id) block_id = base64.encodestring(str(idx)).strip() try: blob.stage_block(block_id, data) return HttpResponse(status=200, content="ok", content_type='text/plain') except Exception, ex: import traceback logger.error(traceback.format_exc()) return HttpResponse(status=500, content="failure", content_type='text/plain') The uwsgi config is like below: master = true single-interpreter = true processes = 8 enable-threads = true threads = 20 socket = /tmp/instance.sock chmod-socket = 666 listen = 8192 harakiri = 90 vacuum = true buffer-size … -
Stepwise procedure to install django,nginx,gunicorn,supervisor and virtualenv on Fedora 38
Steps: NGINX 1.Installed ningx, added a test index page at /etc/nginx/sites.d Added an include /etc/nginx/sites.d/*.conf; in the main nginx conf.d file. It worked out of the box, (I didn't go for any of the sites-available sites-enabled symnliks alternative configurations which never worked and were downright complicated) POSTGRESQL 2. Installed postgresql, created db and owner and granted privs. Now my questions on how to continue: VIRTUALENV: a) I INSTALLED virtualenv, have not CREATED it yet to anywhere nor ACTIVATED it. I read it can be created anywhere, QUESTION: I read creating a webapps dir at the root is ok? b) once I have question 3.a) cleared, next topic: CLONING THE DJANGO APP FROM BITBUCKET I have my django app at bitbucket. QUESTION: do I have to place myself where the test index page is (step 1) to start the cloning from the repository? or do I do it from the webapps dir created at 3a) ? GUNICORN Since gunicorn is a python package, it has to have the virtualenv installed before (unlike postgresql and nginx who are self-contained) Still inside the activated virtualenv, I will install gunicorn. Since the configuration is very specific I will try that first myself. SUPERVISOR 6) …