Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I display django form in modal window on homepage?
The form works correctly in a register.html file but when I put inside the modal window on my home page the fields aren't displayed and the button doesn’t actually work. My home.html file: {% load i18n %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>{% trans 'Блог страдальцев' %}</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <body> <div class="g-image"; style="background-image: linear-gradient( 112.1deg, rgba(32,38,57,1) 11.4%, rgba(63,76,119,1) 70.2% ); min-height: 100vh"> <header> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="/">{% trans 'Блог страдальцев' %}</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Переключатель навигации"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">{% trans 'Главная' %}</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">{% trans 'О блоге страдальцев' %}</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {% trans 'Разделы блога' %} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="/pozn">{% trans 'Страдальческий' %}</a></li> <li><a class="dropdown-item" href="/len">{% trans 'Не страдальческий' %}</a></li> <li> <hr class="dropdown-divider"> </li> <li><a class="dropdown-item" href="/superlren">{% trans 'Очень страшно' %}</a></li> </ul> </li> <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal"> Окошечко </button> <!-- Модальное окно --> <div … -
Download all the processed files generated on the fly as zip file on client side (without saving processed files on Server/Database) in Django Python
I want to download all the processed files generated in a program as a zip file on client system on the fly without storing them on the server/database side. I am working on Django framework. The idea is to take multiple files as input from the user, perform some processing on excel files and then download those files as a single zipfile (on the fly) at the client end without storing them on server To achieve this, what I did is: **In my views.py file:** from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import zipfile import pandas as pd import io # creating a zip file object outside any function so that its accessible to all the functions in the views.py file (**Not sure if this is the right way of doing it**) zipObj = ZipFile('sample.zip', 'w') # This function identifies if the file is excel def myfiletype(fname): filename = fname # Get file extension file_ext = filename.split(".")[-1] # check if extension matches type of file we expect: if file_ext.lower() in ("xls", "xlsx"): return "excel" return "unrecognized" @csrf_exempt def files_processing(request): if request.method == "POST": files = request.FILES.getlist('file') # process each file: for file in files: if myfiletype(str(file)) == 'excel': excel_processor(file) … -
Django error on deleting a user in the admin interface
Somewhere between my development machine and my deployment machine (still in testing thank god), the migrations got jumbled. I am not sure what is going on or how to fix, I found the error just by simply going to the admin and deleting a user. I think the migrations got jumbled between my development box and deployment box (thats still in testing thank god) The error I get when I try to delete the user is in debug.log and it says: django.db.utils.ProgrammingError: column programscheduler_proposal.program_id does not exist LINE 1: SELECT "programscheduler_proposal"."id", "programscheduler_p... ^ HINT: Perhaps you meant to reference the column "programscheduler_proposal.programID". So the models being referenced are: class Proposal(models.Model): objects = models.Manager() program = models.ForeignKey("Program", on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) title = models.CharField(max_length=100) scheduler = models.ForeignKey('accounts.APOUser', on_delete=models.CASCADE) pi = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_related', on_delete=models.PROTECT) #observers recahback to proposal observer. untrained_observer_list = models.CharField(max_length=200) #just seperate via commas collaborators = models.CharField(max_length=200) #just seperate via commas ... ... class Program(models.Model): programName = models.CharField(max_length=100) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) Then under accounts class APOUser(models.Model): objects = models.Manager() user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.Institution", on_delete=models.SET_NULL, null=True) gender = models.ForeignKey("mainpage.GenderTable", on_delete=models.SET_NULL, null=True) on_site_status = models.ForeignKey("mainpage.SiteStatus", on_delete=models.SET_NULL, null=True) refer_to_as = models.TextField(max_length = 30, blank=True, null=True) #if the above … -
Sending files with Web socket
I want to create a chat using web socket (django-channels). And I have a problem, when I try to upload file data about him goes into a variable text_data in receive() function. Maybe It's more problems with code, and i will be grateful for any help. Here is a code chat_room.js: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); chatSocket.onerror = function(event) { document.querySelector('body').innerHTML = '<h1>Chat does not exist</h1>'; }; chatSocket.onmessage = function(e){ console.log(1) const data = JSON.parse(e.data); if (data.message){ console.log(2) let messange = document.createElement('li') messange.textContent = data.message document.querySelector('.chat-log-list').appendChild(messange); } else if(data.file){ console.log(3) let message = document.createElement('li') let link = document.createElement('a') link.textContent = data.file.filename; link.href = data.file.url link.target = '_blank' message.appendChild(link) document.querySelector('.chat-log-list').appendChild(messange); } } chatSocket.onclose = function(e){ console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if(e.keyCode === 13){ document.querySelector('#chat-message-submit').click(); } } document.querySelector('#chat-message-submit').onclick = function(e){ const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value const fileInputDom = document.querySelector('#chat-file-input'); const file = fileInputDom.files[0] if (file){ const reader = new FileReader(); reader.onload = (event) => { const fileData = event.target.result; chatSocket.send(JSON.stringify(fileData)) } reader.readAsDataURL(file) } else if(message){ chatSocket.send(JSON.stringify({ 'message': message })); } fileInputDom.value = '' messageInputDom.value = ''; } consumers.py: import json from .models import * … -
Django NoReverseMatch Solution?
I am carrying out a project for an online grocery store. I want to have a 'View Ratings' button beneath each item within the store that takes users to a ratings.html page where they can view previous ratings and also submit their own using a form. However, I am running into the following error when I attempt to click the 'View Ratings' button beneath an item. Also, if i managed to get this fixed, is there a way I can make it so I can view the ratings in my admin area. Any help appreciated! Reverse for 'ratings' with arguments '('',)' not found. 1 pattern(s) tried: ['ratings/(?P<item_id>[0-9]+)/\\Z'] Request Method: GET Request URL: http://localhost:8000/ratings/1/ Django Version: 4.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'ratings' with arguments '('',)' not found. 1 pattern(s) tried: ['ratings/(?P<item_id>[0-9]+)/\\Z'] Exception Location: C:\Users\Sammc\OneDrive - Ulster University\Desktop\django_project\venv\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: customer.views.Ratings Python Executable: C:\Users\Sammc\OneDrive - Ulster University\Desktop\django_project\venv\Scripts\python.exe Python Version: 3.10.7 Python Path: ['C:\\Users\\Sammc\\OneDrive - Ulster ' 'University\\Desktop\\django_project\\groc', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Users\\Sammc\\OneDrive - Ulster ' 'University\\Desktop\\django_project\\venv', 'C:\\Users\\Sammc\\OneDrive - Ulster ' 'University\\Desktop\\django_project\\venv\\lib\\site-packages'] Server time: Thu, 04 May 2023 14:54:43 +0000 Error during template rendering In template C:\Users\Sammc\OneDrive - Ulster University\Desktop\django_project\groc\customer\templates\customer\ratings.html, error at line 15 Reverse for … -
Static css is not implementing in django templates
I made this project for my own learning about 2 months back. That time all things were working properly . After that today, I again ran this project but this time static css is not being applied on templates. I could not find any issue. Please help me with this. This is the folder outlet This is the setting code This is base template code that is extended in other html -
i dont know How to fil out and 'priant' a convocation IN DJANGO?
hi i have a problème in Django i dont know How to fil out and 'print' a convocation IN DJANGO ? I dont know how start the problem. I do some 'recherche' but no one talk about this problem -
500 Error When Accessing robots.txt File in Django App Hosted on HestiaCP: Need Help Fixing the Issue
I just tried to publish web-site using the Django App, the organization gave me the HestiaCP for host it. Everything works grate, but I have one and only problem. When I tryed to get the robots.txt file it gives me the 500 error. It still work correctly when I run it on the localhost. enter image description here enter image description here Hestia gave me that log: 353868 could not find named location "@fallback", client: ***.***.***.***, server: *************.***, request: "GET /robots.txt HTTP/1.1", host: "*****************.***" I hide the ip and site name by the *. Sorry for that. But still. I thought that its not a problem when Bing index that page, but when I goes into Google search console... It even cant parse the sitemap.enter image description here Have someone know what I should to do? I have no idea how to fix it. But here you can give me some useful tips for fix it. I hope someone know how fix it. -
Error message for deploying Django app to Azure
Is anyone able to explain why I'm getting this error message when trying to deploy my django-python app to Azure via the VS Code Azure Tool Extension? "This region has quota of 0 instances for your subscription. Try selecting different region or SKU." I'm on a free trial with Azure. I followed the instructions from this tutorial https://learn.microsoft.com/en-us/training/modules/django-deployment/6-deploy-azure but have not been able to proceed past the 'create web app' stage. -
Module not found error in Python script running as a Windows Service
I have a Django "learning project" which hosts a very simple web site, with waitress providing the WSGI server. The project performs as expected when I execute the calling script from the command line. From here I'm trying to set up the scaffolding to have it run as a Windows Service. I installed pywin32 and servicemanager to my virtual environment, and -- later on, trying to resolve an error -- also installed them to my "real" Python instance on the machine. Despite this, I keep getting a ModuleNotFoundError error, citing servicemanager, when I try to start the created service: This Python script I'm using; it is based on a template script I found here. import win32serviceutil import win32service import win32event import servicemanager import socket from waitress import serve from django_project.wsgi import application class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "PagesService" _svc_display_name_ = "Pages Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): serve(application, port='8000') if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) As noted above I've installed servicemanager to both the virtual environment and the "real" environment, I've followed the classic Roy request and rebooted the machine just to be sure. Here's the requirements.txt … -
Trying to Debug Dynamic Forms in Django - logging SQL
Context: I've recently taken on Web Development responsibilities at my job. I'm not 100% familiar with Django or our codebase yet. Our staff intranet has dynamic forms for different accident reports. We have a non-employee accident report that functions perfectly, and an employee accident form that is currently not functioning. The code is nearly identical less a few different fields for each. When the form is submitted, the page will provide a summary of the info you entered to be approved for publication. This works on the non-employee form, but not on the employee form. When I submit the bugged form, the form data exists in the payload and the post request returns a 200 response. At this point we are thinking that it is a database issue, but there isn't any debugging implemented. We are trying to implement some debugging, but I can't get anything to display in the console, though I do think I am pretty confused. IMPORTANT NOTE: We are on a super outdated version of django: 1.11 This is what I have in my settings.py file. Everything I have found and read online says that this should print SQL statements to the console. But I'm not … -
Case-insensitive collation for django field
After upgrading to django 4.2, I changed an email field from CIText into TestField with db collation. However, after the update the field does not seem to be case insensitive (for example querying by email "example@example.com" returns an instance and querying by email "Example@example.com" does not) Here's what I did: Created a new db collation for CI operations = [ CreateCollation( name="case_insensitive", provider="icu", locale="und-u-ks-level2", deterministic=False, ) ] Changed the field from a CITextField to a TextField with the new collation and applied this change's migration email = models.TextField( max_length=255, db_index=True, db_collation="case_insensitive", ) I am using Postgres 12 What else is needed to define a field as a CI? Thanks! -
Django Postgres Docker First Migration Failing
I am having some difficulty in setting my app up to be dockerised. It runs locally without a problem using sqlite. I can delete the sqlite db and run the migrations from scratch and then migrate each of the apps after that. I can make all the migration files in advance and then delete the sqlite db and run it again from the command line and run manage.py migrate and all tables are created correctly. All good. However! When I try and dockerise it it all seems to fall apart. Here is my docker-compose file which creates the postgres container and the django container correctly and I can shell into the django container and connect to the database from the command line using psql and the configured parameters. version: '3.8' services: web: build: context: . ports: - 80:8000 depends_on: db: condition: service_healthy environment: - DATABASE_ENGINE=django.db.backends.postgresql - DATABASE_NAME=project - DATABASE_USER=project - DATABASE_PASSWORD=postgres - DATABASE_HOST=db - DATABASE_PORT=5432 - PORT=8000 - DEBUG=False #command: python3 manage.py runserver 0.0.0.0:8000 command: ping google.com networks: - project-network db: image: postgres:15.2-alpine environment: - POSTGRES_USER=project - POSTGRES_PASSWORD=postgres ports: - 5432:5432 networks: - project-network healthcheck: test: "pg_isready --username=project && psql --username=project --list" timeout: 10s retries: 20 networks: project-network: name: project_network … -
500 (Internal Server Error) Django and Vue.js
When I try to submit a form from vue.js, this error shows up, everything else works correctly, all I need is to send the form to my django project / views to treat the data the thing that doesnt happens due to this error here is my submit function: handleSubmit(){ if(this.nom == '') this.nameError = "Vous devez saisir votre nom" this.pwdLengthError = this.password.length >= 5 ? '' : 'Le mot de passe doit contenir 5 caracteres au minimum !' console.log(this.pwdLengthError) if(this.password != this.passwordConfirm) this.pwdConfirmError = "Vous n'avez pas saisi le meme mot de passe" else this.pwdConfirmError = '' console.log(this.pwdConfirmError) const consultant = { nom: this.nom, prenom: this.prenom, username: this.username, password: this.password, email: this.email, telephone: this.telephone, adresse: this.adresse, } axios .post('/createConsultant/', consultant) .then( res => { console.log(res) } ) .catch( err => { console.log(err) } ) }` and the createConsultant in views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import Consultant @csrf_exempt def createConsultant(request): if request.method == 'POST': nom = request.POST.get('nom') prenom = request.POST.get('prenom') username = request.POST.get('username') email = request.POST.get('email') telephone = request.POST.get('telephone') adresse = request.POST.get('adresse') password = request.POST.get('password') print(nom, prenom) consultant = Consultant(nom=nom,prenom=prenom,username=username,email=email,telephone=telephone,adresse=adresse,password=password) consultant.save() return HttpResponse('Consultant created successfully') I already have the url … -
It says that the sender and **kwargs arguments are not working? I am trying to use post save and post delete signals
Here is the image of code also this is not accessable -
Saving file asynchronously on Django
I have a Django storage (boto3) that saves my files at some point during request/response cycle. I need to speed up the cycle, so I decided to save the file in an async manner. my code (storage) from asgiref.sync import sync_to_async from storages.utils import clean_name import asyncio class FileStorage(S3Boto3Storage): bucket_name = '####' async def _save(self, name, content): # save it in async mode await asyncio.create_task(sync_to_async(super()._save)(name, content)) # return super()._save(name, content) return clean_name(name) But I am getting this error now: File "...lib/python3.9/site-packages/django/core/files/storage.py", line 58, in save validate_file_name(name, allow_relative_path=True) File "....lib/python3.9/site-packages/django/core/files/utils.py", line 9, in validate_file_name if os.path.basename(name) in {"", ".", ".."}: File "...lib/python3.9/posixpath.py", line 142, in basename p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not coroutine -
I am facing issue in django [closed]
showing error :ImportError: cannot import name 'roll_dice' from 'utils' ` i am trying to solve - -pip install 'utils' make utils.py new dictionary But issue is not solved -
How to fix empty csv file after downloading from HTML website with Python in Django?
Looking forward to fix empthy csv file issue inside my Django project. I'm testing Youtube API where I'm fetching suggestion to my youtube.html website. I created Download as CSV button and after cliking it I'm downloading empty csv file. My source code in Github here: https://github.com/Vy7au7as/API.git Any suggestions how to download all results to csv WITHOUT saving inside database? I'm trying to download all results into csv file, but files it's empty... -
How to remove a tag when scraping
<p class="hidden-xs text-muted"> <b>GMC:</b> 123456 </p> I simply need the GMC number from here which will appear as GMC : 123456 when I scrape it. How to remove the "b" tag from there? I am using python 3.10.5 and BeautifulSoup. from bs4 import BeautifulSoup import requests def proxy_request(url): response = requests.get(url) return BeautifulSoup(response.text, 'lxml') url = "www.domain.com" # not mentioning the domain here soup = proxy_request(url) media_body = soup.find("div", {"class":"media-body"}) gmc_number = media_body.p.text.strip() output is like this, GMC: 123456 expected output, 123456 -
how can i provide a confirmation form in the properties_list view before deleting the property
the code below deletes the property directly when the user clicks the delete btn, how can i edit the code to provide a confirmation form i.e modal where the user can choose to either delete or not. views.py def property_list(request): properties = Property.objects.all() context = { 'properties': properties, 'delete_template':'real_estate/property/delete.html', } return render(request, 'real_estate/property/list.html', context) def delete_property(request, id): property = get_object_or_404(Property, id=id) if request.method == 'POST': property.delete() messages.success(request, f"you have successfully deleted {property.title}") return redirect('real_estate:property_list') context = { 'property': property, 'confirm_template':'real_estate/property/delete.html', 'confirm_url': reverse('real_estate:delete_property', args=[property.id]) } return render(request, context['confirm_template'], context) real_estate/property/list.html' {% extends "real_estate/base.html" %} {% block title %} Property List {% endblock %} {% block content %} {% if properties %} <h1>properties list</h1> <a class="btn" href="{% url 'real_estate:add_property' %}" >add property</a> <ul> {% for property in properties %} <li> <a href="{% url 'real_estate:property_details' property.id %}"> {{ property.title }} </a> <a class="btn btn-primary" href="{% url 'real_estate:property_details' property.id %}">View</a> <a class="btn btn-warning" href="{% url 'real_estate:edit_property' property.id %}">Edit</a> {% if request.GET.delete and request.GET.delete == property.id %} {% include confirm_template with property=property %} {% else %} <form action="{% url 'real_estate:delete_property' property.id %}" method="post"> {% csrf_token %} <button type="submit" name="delete">Delete</button> </form> {% endif %} </li> {% endfor %} </ul> {% else %} <h1>no properties added</h1> <a … -
getting static file for django with nginx
im trying to get static files in django, when using an nginx reverse proxy, dockerized in an ec2 container i have a django project and when it is dockerized with nginx as a proxy server i can not find my static files my default-ssl.conf.tpl for my nginx server has location /static{ alias /vol/static; } and my dockerfile for nginx says to creates a volume for vol/static VOLUME /vol/static VOLUME /vol/www so i manually put my files in there with docker cp and check with exec to make sure they're there my files are now in vol/static on my proxy container. so i think they should be handled properly now i still get GET https://tgmjack.com/static/health_hud.png 404 (Not Found) :( what might i have done wrong? what other info would be useful? my full code is here incase that might reveal what ive done wrong https://github.com/tgmjack/god_help_me extra info im deploying on an ec2 container i can connect to my custom domain with https and everything seems to be fine except the files cant be found -
HTMX load partials based on URL
Question: How do I have HTMX load a partial based on a URL that the user manually navigated to? I am using HTMX to load HTML partials. All partials come from their own endpoint. So in this example, it is coming from /h/library/1 where as the page is simply /library/1 My URL patterns are as such: urlpatterns = [ path("", login_required(views.logged_in_home), path("library/<id>", login_required(views.logged_in_home)), path("h/library/<id>", login_required(views.show_library)), # returns partial ] The button to load the library looks like this: <a hx-get="/h/library/1" hx-push-url="/library/1" hx-target="#page-content" hx-swap="innerHTML" > Load Library 1 </a> <div id="page-content"></div> When I click the link, the partial gets loaded correctly into the div and the url updates with /library/1. However, when I manually navigate to /library/1, I get the homepage, but the partial doesn't load. What the heck am I doing wrong? I see a lot of responses that suggest looking at the HTMX headers to determine if a partial or full page should be sent back, but I thought I could easily side-step that by using a designated api prefix like /h/* -
Passing data from frontend to backend, JS and Django
I am trying to pass data for the shipping option that a customer selects in this form: <label>Shipping option:</label> <select name="shipping_option" id="shipping_option"> <option value="">Select an option</option> {% for shipping_option in shipping_options %} <option value="{{ shipping_option.cost }}" data-id="{{shipping_option.id}}" data-cost="{{ shipping_option.cost }}" {% if selected_shipping_option == shipping_option.id %}selected{% endif %}> {{shipping_option.id}} - {{ shipping_option.name }} - £{{ shipping_option.cost }} </option> {% endfor %} </select> I am using this script which successfully logs the correct shipping_option.id: onApprove: function(data, actions) { var shippingOption = document.getElementById('shipping_option'); var selectedShippingOption = shippingOption.options[shippingOption.selectedIndex]; var shippingOptionId = selectedShippingOption.getAttribute('data-id'); var shippingOptionCost = selectedShippingOption.getAttribute('data-cost'); console.log('shippingOptionId:', shippingOptionId); return fetch('/capture_payment/', { method: 'POST', headers: { 'content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ orderID: data.orderID, shipping_option_id: shippingOptionId, shipping_option_cost: shippingOptionCost }) }).then(function(response) { return response.json(); }).then(function(captureData) { updateOrder(); }); } }).render('#paypal-button-container'); </script> I am then trying to pass this data to my update_order util which then adds the shipping_option to the order that has been placed, but i keep getting the error: KeyError: 'shipping_option': def update_order(request): data = json.loads(request.body) print('SHIPPING', data) customer = Customer.objects.get(user=request.user) order = Order.objects.filter(customer=customer, order_status='P').order_by('-id').first() transaction_id = datetime.now().timestamp() total = order.get_order_total shipping_address = ShippingAddress.objects.filter(customer=customer).order_by('-date_added').first() # Retrieve the selected shipping option from the request payload if order.order_status == 'P': order.order_status = 'C' order.transaction_id … -
The task is being received but I do not receive a notification that it has been executed
The task is being received but I don't get a notification that it is executed I want to know if the task is running import logging from celery.utils.log import get_task_logger logger = get_task_logger(name) logger.setLevel(logging.INFO) @shared_task def add(x, y): return x + y @api_view(["GET"]) def deneme(request): eta_time = datetime.now() + timedelta(minutes=1) result = add.apply_async((3,5),eta=eta_time, result=True) logger.info('Task %s succeeded in %s seconds: %s', result.task_id, result.result) return Response("Deneme") the result i expected [2023-05-04 14:09:14,515: INFO/MainProcess] Task challenge.task.add[f4a7a3dc-d774-41a3-8aa3-3a7e8f7895b2] succeeded in 0.0779999999795109s: 8 -
Access to model attributes and methods in Django 4.2 after async call for model object
How to access to model attributes and methods in Django 4.2 after async call for model object? Here is my model: class ProjectModule(models.Model): ... url = models.URLField(verbose_name="URL") ... I'm getting a coroutine with this func: async def get_module_object(module_id: int): """Get module object.""" try: return await ProjectModule.objects.aget(pk=module_id) except Exception as e: return HttpResponseServerError(f"Error: {e}") After that I query a url with next async function: async def call_url(url: str): """Make a request to an external url.""" try: async with aiohttp.ClientSession() as session: async with session.get(url=url) as response: return response except Exception as e: print(e) return web.Response(status=500) Finally in my next function I call for model and url and trying to get model object from coroutine async def htmx_test_run_module(request, module_id: int): """Test run module with HTMX request.""" if request.method == "GET": try: module_coroutine = await get_module_object(module_id=module_id) module = await module_coroutine # first error is here response = await call_url(url=module.url) response = await response_coroutine # second error is here soup = BeautifulSoup(response.text(), "lxml") tag = soup.find( module.container_html_tag, class_=module.container_html_tag_class ) return HttpResponse(tag) except Exception as e: return HttpResponseServerError(f"Error: {e}") The first error is Error: object ProjectModule can't be used in 'await' expression and the second one is Cannot find reference 'await' in 'ClientResponse | Response'. …