Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) … -
Integrating Databricks SQL Connector with Django ORM for CRUD Operations
I am working on a Django project that requires integration with Databricks, and I am currently exploring the use of the databricks-sql-connector Python package for connectivity. However, my concern is that utilizing this package might involve manual SQL query creation for CRUD operations within my Django project. Is there a method available that allows me to establish a connection to the Databricks database while still leveraging Django's ORM capabilities? I would like to achieve a connection similar to the following code snippet: sql.connect( server_hostname=connection_params["hostname"], http_path=connection_params["http_path"], access_token=connection_params["access_token"] ) Additionally, I would like to extract a cursor using the following snippet: connections["default"].cursor() My database settings are configured as follows: DATABASES = { 'default': { 'ENGINE': 'custom_engine_name', 'HOSTNAME': os.getenv('DATABRICKS_HOSTNAME'), 'NOTEBOOK_PATH': os.getenv('DATABRICKS_NOTEBOOK_PATH'), 'ACCESS_TOKEN': os.getenv('DATABRICKS_ACCESS_TOKEN'), } } My expectation is to find a method or solution that allows me to establish a connection to the Databricks database using Django's ORM, avoiding the need for manual SQL queries. If this requires writing a custom adapter, I would appreciate guidance on how to create one that effectively connects Django ORM with the "databricks-sql-connector." -
Place N number of points having height and width in the sector area of radii of the two concentric circles with radius r1 and r2
Place N number of points having height and width in the sector area of radii of the two concentric circles with radius r1 and r2 In given image i want to place 5 points inside the area enter image description here place it evenly like this : enter image description here using python code , assume that i have made circles and we have radius r1 and r2 and sector angle -
How to configure HSTS in django
I need to configure hsts in one of django app. I have read django doc and came to a point that if I set SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True It will set hsts header on all request headers which it didn't Additionally I got another key value SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') That I need to set if my app is behind proxy. I expect that on all of my django api request headers I see that hsts header. -
How to run Huey consumer on Windows IIS
I am working on a Django application which is deployed on a Windows Server using IIS. I want to use Huey to be able to run background tasks e.g. sending of emails and report generation. Celery does not support Windows hence my decision to use Huey. According to the documentation, you can run the consumer using the following command: ./manage.py run_huey My question is, how and where will I need to run this command to work with my setup i.e. Windows and IIS? It should also work when the server is restarted. -
How to check email validation using regex in Django
I'm trying to create a registration form for my Django project. I want to check if the user's email address is correct. I used built-in email validator, but it just check the domain. I need to prevent user to enter emails like this: john#doe@gmail.com etc. here is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=300, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True, validators=[validate_email]) username = models.CharField(max_length=200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.user.username) forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['first_name', 'email', 'username', 'password1', 'password2'] labels = {'first_name':'Name',} signals.py @receiver(post_save, sender=User) def createProfile(sender, instance, created, **kwargs): if created: user = instance profile = Profile.objects.create( user = user, username = user.username, email = user.email, name = user.first_name, ) and views.py for registration def registerUser(request): page = 'register' form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() messages.success(request, 'User Account Was Created!') login(request, user) return redirect('profile') else: messages.error(request, 'An error has accurred during registration!') context = {'page' : page, 'form' : form} return render(request, 'users/login-register.html', context) -
KeyError at / 'daily'
current_weather_url = 'https://api.openweathermap.org/data/2.5/weather?q={}&appid={}' forecast_url = 'https://api.openweathermap.org/data/3.0/onecall?lat={}&lon={}&exclude=current,minutely,hourly,alerts&appid={}' def fetch_weather_and_forecast(city, api_key, current_weather_url, forecast_url): response = requests.get(current_weather_url.format(city, api_key)).json() lat, lon = response['coord']['lat'], response['coord']['lon'] forecast_response = requests.get(forecast_url.format(lat, lon, api_key)).json() weather_data = { 'city': city, 'temperature': round(response['main']['temp'] - 273.15, 2), 'description': response['weather'][0]['description'], 'icon': response['weather'][0]['icon'], } daily_forecasts = [] for daily_data in forecast_response['daily'][:5]: daily_forecasts.append({ 'day': datetime.datetime.fromtimestamp(daily_data['dt']).strftime('%A'), 'min_temp': round(daily_data['temp']['min'] - 273.15, 2), 'max_temp': round(daily_data['temp']['max'] - 273.15, 2), 'description': daily_data['weather'][0]['description'], 'icon': daily_data['weather'][0]['icon'], }) return weather_data, daily_forecasts --- THIS IS THE FORECAST REPONSE THAT I GET forecast_response {'cod': 401, 'message': 'Invalid API key. Please see ' 'https://openweathermap.org/faq#error401 for more info.'} Actually i am creating a weather app where i used api from https://home.openweathermap.org/ but while using the forecast url in the above function in the for loop for daily_forecasts it says that >>>KeyError at / 'daily' and the line having mistake is shown to be >>>for daily_data in forecast_response['daily'][:5]: In the for loop for daily_forecasts, I'm encountering a KeyError related to the 'daily' key in the OpenWeatherMap API response. I've verified my API key and the overall structure of the response, but I seem to be missing something crucial. please fix this it says that daily is not there but it is there .