Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does subprocess.Popen.wait deadlock when using file type for stdout?
Any help is appreciated. I have a custom Django command and a method like the one below: def read_status_to_list(self) -> List[str]: with open('git.txt', 'w+') as temp: status = subprocess.Popen(['git', 'status'], stdout=temp) status.wait() statuses = [line.split()[-1] for line in temp.readlines() if 'modified:' in line ] # remove file when done if os.path.isfile('git.txt'): os.remove('git.txt') return statuses However, statuses is always empty even when git status produces a number of modified modules not added yet. I noticed a warning in the wait method: Warning: This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that. Is this warning related to the problem, and how can I successfully complete this task using subprocess? Thank you. -
Django Interview Question for showing the result in coding
While showing my project by sharing the screen, I explained my project which is on Student Management System to interviewer but he was kept asking me about show me the result in code. I'm fresher and I haven't used python Django much so can anyone explain me what result should I show to the interviewer? I have done that project by watching tutorials on Student Management System. What do they expect us to show? YouTube Link - https://youtu.be/FMPpaTFdL2k I explained him the overall working of code. I showed him backend admin panal and also python code fies urls settings models views. But he was keep repeating show me the result. Please explain me someone how can I show the result. -
how to filter the data from django database for a week?
I'm filtering the data from django database using datetime__range filter providing the dates start_of_week and end_of_week and I have another list in python that contains the dates of that week so when I got the data from the range filter I count it for each day using the date from the week but for some users the result I got contain the data of one day earlier so it shows error because the result contain I date earlier of start_of_week date which was not in week_dates list so it shows key error. How Should I filter the data so that I got proper data between the range. I'm adding the models.py and admin.py and the screenshot of terminal. `the model of User_details in models.py SUGESSTION_CHOICES = ( (0,'Pending Verification'), (1, 'User Accepts Prediction'), (2,'User Suggestion Incorrect'), (3,'Actual Prediction Incorrect'), (4,'Unsupported Breed'), (5,'In Progress'), (6,'Model Successfully Trained'), ) PREDICTION_CHOICES = ( (0,'By Image'), (1, 'By Video') ) PREDICTION_STATUS = ( (0,'Predicted Sucessfully'), (1, 'Not Able To Predict'), (2, 'Junk'), ) class History(models.Model): user= models.ForeignKey(User_details, related_name='history', on_delete=models.CASCADE) image=models.ImageField(upload_to=get_upload_path,null=True) predictions= models.TextField(default=dict(),null=True,verbose_name="Predictions") predictions_type=models.IntegerField(choices=PREDICTION_CHOICES, default=0,verbose_name="Prediction Type") predictions_status=models.IntegerField(choices=PREDICTION_STATUS, default=0,verbose_name="Prediction Status") predicted_breed_id = models.PositiveIntegerField(null=True,blank=True,verbose_name="Predicted Breed Id") moods= models.TextField(default=dict(),null=True,verbose_name="Moods") user_platform= models.CharField(max_length=50,default='',null=True,verbose_name="User Platform") user_device= models.CharField(max_length=50,default='',null=True,verbose_name="User Device ID") app_version= models.CharField(max_length=50,default='',null=True,verbose_name="App … -
Form in Django not saving my article to database
I am making a blog/articles page in django, and whenever I try to enter some input, it doesn't save to the database. I have tried re-running the server, refreshing, still it doesn't save. I am getting no errors, 200 code meaning it's all OK. views.py @login_required(login_url="/accounts/login/") def new_article(req): if req.method == 'POST': form = forms.CreateArticle(req.POST, req.FILES) if form.is_valid(): #save article to database instance = form.save(commit=False) instance.author = req.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(req, 'articles/createArticle.html', {'form': form}) createArticle.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Article Home Page</title> <link rel="stylesheet" href="/static/styles.css"> </head> <body> <a href="{% url 'articles:list'%}"><img src="/static/logo.png" alt="TBD"/></a> <nav> <ul> <li> <form class="logout-link" action="/accounts/logout/" method="post"> {% csrf_token %} <button type="submit">Log Out</button> </form> </li> </ul> </nav> <div class="create-article"> <h2>Write your own Article!!</h2> {% csrf_token %} <form class="newArticleForm" action="/articles/create/" method="post" enctype="multipart/form-data"> {{ form }} </form> <input type="submit" value="Create"> </div> </body> </html> models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Articles(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, default = None, on_delete=models.CASCADE) def __str__(self): return self.title def snippet(self): return self.body[:50]+'...' I am following Net Ninja Django Tutorial and have been … -
AbstractUser django
abstractuserI created user AbstractUser to be a standalone user and to log in via this user Unfortunately when I create a user and log in through that user it tells me the username and password Error login page for admin django verifies the default username and password and does not authenticate with the user you created AbstractUser What is the solution for the admin django login page to verify the partition created by user django admin. admin2. admin3. forms. models. settings. view. -
Cannot connect MySQL in a Django project docker container
First, I installed Docker v4.20.1 in my Windows 10. I run docker compose successfully and their status are as the following screenshot. my phpmyadmin container can access mysql db successfully as the following screenshot. If I run the django project in my host computer(Windows 10), it also connect mysql db successfully. But If I try to run the django server in the web container, it shows up the error message that it can't connect mysql db correctly. The error logs: root@80c6e906cf7e:/usr/src/app# python caravan/manage.py migrate Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 291, in _open_connection self._cmysql.connect(**cnx_kwargs) _mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on '127.0.0.1:3306' (111) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/django/base.py", line 399, in get_new_connection cnx = mysql.connector.connect(**conn_params) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/pooling.py", line 293, in connect return CMySQLConnection(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 120, in __init__ self.connect(**kwargs) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/abstracts.py", line 1181, in connect self._open_connection() File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 296, in _open_connection raise get_mysql_exception( mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (111) The above exception … -
Celery not running new task
I've readded an old Celery task to my Django app running on Heroku, but it's not being run by the worker. The task appears in the tasks when the worker starts, and I can see the scheduler sending it to the worker. However, it is never received by the worker. What can I do to troubleshoot this issue? Other tasks added are running fine and it runs fine on the staging server which is another instance on Heroku. I've tried restarting all the dynos and changing the name of the task and repushing it but that hasn't worked. -
Unable to understand the bug in views.py
This is my views.py in which I have created the class Pizza. from django.shortcuts import render from .models import Pizza def index(request): pizzas = Pizza.objects.all() return render(request, 'menu/index.html', {'pizzas ':pizzas}) And this is the html file: <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Pizzas</title> </head> <body> <h1>Our Pizzas</h1> <ul> {% for pizza in pizzas %} <li>{{pizza.name}}</li> {% endfor %} </ul> </body> </html> In the result the page should have given me the names of pizzas stored in the class pizza but it is giving me only what is inside <h1></h1> This is what I get When I inspect the html page it gives me this: enter image description here There is nothing between the <ul></ul> When I run the debugger for the views.py file, it gives me: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Please suggest solution -
How do I add custom attributes autocomplete to crispy_forms Django
I would like to check how do I add the autocomplete attribute to the crispy_forms. Any help would be appreciated. Thanks. -
How to filter model by foreign key field of FK field?
I have model 'Employee': class Employee(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) end_user_id = models.CharField(max_length=8, help_text=u"Please enter the end user id, like ABC1WZ1") history = HistoricalRecords() def __str__(self): return self.name + ' ' + self.lastname Employee can be a manager, so I also have model 'Manager': class Manager(models.Model): id = models.AutoField(primary_key=True) manager = models.ForeignKey(Employee, verbose_name='manager', on_delete = models.DO_NOTHING) def __str__(self): return self.manager .name + ' ' + self.manager .lastname And my main model 'MissForm': class MissForm(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) auto_inc_id = models.IntegerField(blank=True, null=True) sender = models.ForeignKey(Employee, verbose_name='sender', on_delete = models.DO_NOTHING, blank=True, null=True) manager = models.ForeignKey(Manager, verbose_name='Manager', on_delete = models.DO_NOTHING, related_name='+', blank=True, null=True ) status_flag = models.PositiveIntegerField(default=1) I am trying to get all instances of MissForm model where manager is a current logined user and status_flag=2( in views.py): login_user_id = request.user.username.upper() # returns smth like ABC1WZ1 forms = MissForm.objects.filter(status_flag=2, manager__manager__end_user_id=login_user_id) But it doesn't work. What I am doing wrong? -
How to display views.py results directly and dynamically on template.html in django?
I have a django website project with exper.html template and views.py as processing backend. I want when we enter parameters or input in the textarea and after that press the submit button, then views.py can process those parameters and generate images and display them directly in the exper.html template file. below is the code for expert.html and views.py exper.html: <div class="container-area text-center"> <form id="myForm" class="row"> {% csrf_token %} <div class="col-md-12"> <label for="input_text"></label><br> <textarea id="input_text" name="input_text" rows="10" cols="100" placeholder="Write Code Here" required></textarea><br><br> </div> <div class="col-md-12 d-flex justify-content-center align-items-center"> <input type="button" value="Run" onclick="submitForm()"> </div> </form> </div> <script> function submitForm() { const form = document.getElementById('myForm'); const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value; const inputText = document.getElementById('input_text').value; const xhr = new XMLHttpRequest(); xhr.open('POST', ''); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('X-CSRFToken', csrfToken); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { const response = JSON.parse(xhr.responseText); displayImages(response.data_input_img, response.qam_mod_img); } }; xhr.send('input_text=' + encodeURIComponent(inputText)); } </script> views.py def exper(request): if request.method == 'POST': form = ParameterForm(request.POST) if form.is_valid(): input_text = form.cleaned_data['input_text'] subcarrier = 0 mod_order = 0 for param in input_text.split(): if param.startswith('subcarrier='): subcarrier = int(param.split('=')[1]) elif param.startswith('mod_order='): mod_order = int(param.split('=')[1]) data_in = generate_input_data(subcarrier, mod_order) plt.figure() plt.stem(data_in, use_line_collection=True) plt.title('Data Input') plt.xlabel('Indeks Data') plt.ylabel('Nilai Data') plt.grid(True) plt.savefig('static/files/datainput.png') data_input_img_base64 = … -
prefetch_related() without specifying lookups
I encountered such a queryset in a project : qs.prefetch_related().other().methods() Is there a point having such call to prefetch_related() method without specifying any lookup? -
Django - [wsgi:error] [pid 16542:tid 140650901133056] Truncated or oversized response headers received from daemon process
I have googled and tried each and every option but nothing worked . Below are the version specification which is used . Apache/2.4.37 (AlmaLinux) OpenSSL/1.1.1k mod_wsgi/4.6.4 Python/3.6 and mariadb as the database Using Virtual environment Below are my Virtual Configuration paramters with wsgi WSGIDaemonProcess cosmos processes=6 maximum-requests=300 header-buffer-size=65536 connect-timeout=30 python-path=/opt/cosmos/cosmos_api_v3:/opt/cosmos/cosmosenv/lib/python3.6/site-packages/ WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup cosmos WSGIScriptAlias /api /opt/cosmos/cosmos_api_v3/cosmos/wsgi.py WSGIPassAuthorization On Below are installed python packages Package Version amqp 5.0.6 ansible 2.9.0 asgiref 3.4.1 bcrypt 3.2.0 beautifulsoup4 4.11.2 billiard 3.6.4.0 cached-property 1.5.2 celery 5.1.2 certifi 2021.5.30 cffi 1.15.0 charset-normalizer 2.0.6 click 7.1.2 click-didyoumean 0.3.0 click-plugins 1.1.1 click-repl 0.2.0 coreapi 2.3.3 coreschema 0.0.4 crypto 1.4.1 cryptography 35.0.0 Django 3.2.7 django-auth-ldap 3.0.0 django-celery-beat 2.2.1 django-celery-results 2.2.0 django-cors-headers 3.10.0 django-filter 21.1 django-rest-swagger 2.2.0 django-timezone-field 4.2.1 djangorestframework 3.12.4 djangorestframework-jwt 1.11.0 djangorestframework-simplejwt 4.4.0 docopt 0.6.2 humanfriendly 10.0 idna 3.2 importlib-metadata 4.8.1 itypes 1.2.0 Jinja2 3.0.2 kombu 5.1.0 lxml 4.6.3 MarkupSafe 2.0.1 mysql-connector 2.2.9 Naked 0.1.31 openapi-codec 1.3.2 packaging 21.0 pandas 1.1.5 paramiko 2.8.0 pip 21.3.1 prompt-toolkit 3.0.20 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.20 pycryptodome 3.11.0 pyflakes 2.3.1 Pygments 2.10.0 PyJWT 1.7.1 PyMySQL 1.0.2 PyNaCl 1.4.0 pyparsing 3.0.2 python-crontab 2.5.1 python-dateutil 2.8.2 python-dotenv 0.19.2 python-ldap 3.3.1 python-magic 0.4.27 pytz 2021.1 pyvcloud 23.0.3 pyvim 3.0.2 pyvmomi 7.0.2 PyYAML 6.0 … -
I am unable to obtain list of elements from a class created in a python file to display in an HTML file
This is my views.py in which I have created the class Pizza. from django.shortcuts import render from .models import Pizza def index(request): pizzas = Pizza.objects.all() return render(request, 'menu/index.html', {'pizzas ': pizzas}) And this is the html file: <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Pizzas</title> </head> <body> <h1>Our Pizzas</h1> <ul> {% for pizza in pizzas %} <li>{{pizza.name}}</li> {% endfor %} </ul> </body> </html> In the result the page should have given me the names of pizzas stored in the class pizza but it is giving me only what is inside and tags. This is what I get When I inspect the html page it gives me this: enter image description here There is nothing between the and tags. Maybe it is unable to access elements from the class. Please help. -
Authenticating queries in Django Graphene custom nodes with filters and connections?
I'm working on a Django project using Graphene for GraphQL API implementation. I have a custom node called PoemNode which extends DjangoObjectType. I want to authenticate queries made to this node and also include filtering and pagination capabilities using filterset_class and connection_class respectively. I have already set up the authentication backend in Django and have the necessary packages installed. However, I'm unsure how to integrate the authentication logic into my custom node and how to use the filterset_class and connection_class for querying. class PoemNode(DjangoObjectType): class Meta: model = Poem interfaces = (Node,) filterset_class = PoemFilter connection_class = CountableConnectionBase Can anyone guide me on how to authenticate queries for the PoemNode and utilize the filterset_class and connection_class for querying with filtering and pagination capabilities? Thank you in advance for your help! -
how do i convert this query to django orm?
i have a query, how do i convert this query to django orm? SELECT tem.urutan,tem.rentang AS lama_kerja, count(*) as jumlah FROM ( SELECT CASE WHEN employee_join_date IS NULL THEN '1' WHEN EXTRACT(YEAR FROM age(date(now()), employee_join_date)) < 1 THEN '2' WHEN 1 <= EXTRACT(YEAR FROM age(date(now()), employee_join_date)) AND EXTRACT(YEAR FROM age(date(now()), employee_join_date)) <= 10 THEN '3' WHEN 11 <= EXTRACT(YEAR FROM age(date(now()), employee_join_date)) AND EXTRACT(YEAR FROM age(date(now()), employee_join_date)) <= 20 THEN '4' WHEN EXTRACT(YEAR FROM age(date(now()), employee_join_date)) >= 21 THEN '5' ELSE '0' END AS urutan, CASE WHEN employee_join_date IS NULL THEN '<>' WHEN EXTRACT(YEAR FROM age(date(now()), employee_join_date)) < 1 THEN '< 1 Tahun' WHEN 1 <= EXTRACT(YEAR FROM age(date(now()), employee_join_date)) AND EXTRACT(YEAR FROM age(date(now()), employee_join_date)) <= 10 THEN '1 - 10 Tahun' WHEN 11 <= EXTRACT(YEAR FROM age(date(now()), employee_join_date)) AND EXTRACT(YEAR FROM age(date(now()), employee_join_date)) <= 20 THEN '11 - 20 Tahun' WHEN EXTRACT(YEAR FROM age(date(now()), employee_join_date)) >= 21 THEN '> 21 Tahun' ELSE 'Terdefinisi' END AS rentang FROM employees WHERE (employee_resign_date Is Null OR employee_resign_date > date(now())) AND employee_is_resign = '2' ) AS tem GROUP BY tem.urutan,tem.rentang ORDER BY tem.urutan result to this or json enter image description here -
Increase Django CSRF tocken longevity
I get lots of Django CSRF errors due to timeout. In normal operations, the form submissions are OK. But, if I leave the page for a few hours and then submit it, it will fails with the Forbidden (403) CSRF verification failed. Request aborted screen. To overcome this issue, I added the following line to the settings.py : SESSION_COOKIE_AGE = 604800 # one week But a few hours leading to timeout means that this line has had no effect. I need CSRF tokens longevity be increased to a few days rather than minutes. How to achieve this? -
Celery beat_scheduler's task executed but not registered in model django_celery_beat_periodictask
I am trying basic implementation of celery worker and celery beat on the windows PC. The celery beat is sending the task successfully and the celery worker received the task from celery beat and executed the task. The problem is there is no task registered in django_celery_beat_periodictask as expected. Problem: Why there are no task in django_celery_beat_periodictask? Addon questions: If there are no task in django_celery_beat_periodictask then how does the celery beat executing the task? What are the another data sources where celery worker took the task? Project Tree celery_with_django |- django_celery_project |- __init__.py |- settings.py |- celery.py other files |- mainapp |- tasks.py other files |- requirements.txt Command to run the code django server: python manage.py runserver celery worker: celery -A django_celery_project.celery worker --pool=solo -l info **# (without --pool=solo the terminal is hard to interrupt) celery beat: celery -A django_celery_project beat -l info My code look like this requirements.py amqp==5.1.1 asgiref==3.7.2 async-timeout==4.0.2 billiard==3.6.4.0 celery==5.2.7 click==8.1.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 colorama==0.4.6 cron-descriptor==1.4.0 Django==4.2.1 django-celery-beat==2.5.0 django-celery-results==2.5.1 django-timezone-field==5.1 kombu==5.2.4 prompt-toolkit==3.0.38 python-crontab==2.7.1 python-dateutil==2.8.2 pytz==2023.3 redis==4.5.5 six==1.16.0 sqlparse==0.4.4 typing_extensions==4.6.3 tzdata==2023.3 vine==5.0.0 wcwidth==0.2.6 django_celery_project/init.py from .celery import app as celery_app __all__ = ('celery_app',) django_celery_project/settings.py **# other settings **# CELERY SETTINGS CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'django-db' … -
Django Celery running a function multiple times?
In Django, I have created an app for sending emails to clients. I am using Celery Beat to schedule a daily task that executes the schedule_emails function at 12:30 AM. This function runs perfectly. However, I am encountering a problem where the send_email function is running multiple times and sending duplicate emails to specific clients from my email account at the same time. I have checked the logs of the celery worker it shows that a particular task_id was received multiple times and succeed succeeded multiple times. I am using the supervisor to run celery and celery_beat services in the background. settings.py # Celery Settings CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_TASK_ACKS_LATE = True CELERY_RESULT_BACKEND = 'django-db' CELERY_BEAT_SCHEDULE_FILENAME = '.celery/beat-schedule' CELERYD_LOG_FILE = '.celery/celery.log' CELERYBEAT_LOG_FILE = '.celery/celerybeat.log' CELERY_BEAT_SCHEDULE = { 'schedule_emails': { 'task': 'myapp.tasks.schedule_emails', 'schedule': crontab(hour=0, minute=30), }, } celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from decouple import config if config('ENVIRONMENT') == 'development': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings.development') else: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings.production') app = Celery('MyProject**strong text**') app.conf.enable_utc = False app.conf.update(timezone='Asia/Kolkata') app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request : {self.request!r}') task.py from celery import shared_task @shared_task def … -
Is it possible to use functions like gettext() inside Formatted String Literals (F-Strings)
So, is it possible to call a function inside Formatted String Literals (F-String) ? ex: from django.utils.translation import gettext_lazy as _ def func(x): return f'{_("Value")}: {x}' print(func(4)) -
Django Q: build dynamic query from array
For a Django project, I have a dictionary which contains the model name and the columns where to look for. So what I want to achieve is to build the query from the variables coming from my dictionary. sq = [] for x in columns: print(x) sq.append(f'Q({x}__icontains=val)') print(sq) query = (' | '.join(sq)) print(query) lookups = Q(name__icontains=val) | Q(code__icontains=val) # lookups = query When I do the above, it correctly builds the "string" representing the query, but I'm unable to use it. The error is as follows: Traceback (most recent call last): File "/home/user/price_engine/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/price_engine/masterdata/views.py", line 50, in search_form results = Plant.objects.filter(query).distinct() File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1436, in filter return self._filter_or_exclude(False, args, kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1454, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1461, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1534, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1565, in _add_q child_clause, needed_inner = self.build_filter( File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1412, in build_filter arg, value = filter_expr ValueError: too many values to unpack (expected 2) [05/Jul/2023 04:27:27] "POST … -
How to use a background task but i want it to send it using render to specific url
I try to render but it should put request using parameter, how to handle the request when using the background task in django @background(schedule=60) # Runs every 60 seconds def auto_check_status (request): current_time = timezone.now() time_threshold = current_time - timedelta(minutes=10) try: transactions = Transaction.objects.filter( Q(trx_status='PENDING') | Q(trx_status='SUBMITTED'), trx_type_id='R', trx_time__lt=time_threshold ).order_by('trx_time') for transaction in transactions: # Perform actions on each transaction store_database(transaction) message = createrequest(transaction) message = construct_source_string_and_sign(message) npg_url = f"{settings.NPG_URL}/in" npg_url = f"{settings.NPG_URL}/in" return render(request, 'transactions/bayar.html', {'trx': message, 'npg_url' :npg_url}) except Exception as e: print(str(e)) -
Arabic translations not displayed correctly in Django/Celery notification system
I'm currently working on a Django application that includes various functionalities, including notification delivery, in multiple languages. While most of the application works well with Arabic and other languages, I'm facing an issue with Arabic translations in certain parts of the application, including notifications. The Arabic translations are not being displayed correctly, while translations in other languages, such as English and French, work without any issues. Here are the details of my setup: The application uses Django and Celery for task management and background processing. I have added Arabic translations for different text elements in the respective translation files. The Arabic translations work fine in most parts of the application, including UI labels and content. However, when it comes to notifications, specifically in Arabic, the translations are not displayed correctly. Other functionalities, such as database operations, user management, and data processing, work as expected with the Arabic translations. I have ensured that the necessary translations are present, and the language preferences are correctly set for affected users. The issue seems to be specific to the notification tasks triggered by certain actions or events. It's puzzling because the Arabic translations work well in other areas of the application. I would greatly … -
How to connect 2 views in the same Django app? (ListView and EditView)
I have 2 apps called Prospecto(which means Prospect) and Cliente(which means Customer). When you see a register in EditView and click on its checkbox, you can indicate whether the register is still in Prospecto or Cliente If you don't click on the checkbox, that record is still in the Propsecto If you click the checkbox, that record becomes a Cliente and is no longer a Prospect In the code I did, when I clicked the checkbox, it turns into record in Customer(that's ok), but I can't delete it from Prospecto(in ProspectoListView). **views.py class ProspectoListView(ListView): model = Prospecto template_name = 'prospectos.html' context_object_name = 'prospectos' def get_queryset(self): queryset = super().get_queryset() fecha_inicio = self.request.GET.get('fecha_inicio') fecha_fin = self.request.GET.get('fecha_fin') if fecha_inicio and fecha_fin: queryset = queryset.filter(fecha__range=[fecha_inicio, fecha_fin]) elif fecha_inicio: queryset = queryset.filter(fecha__gte=fecha_inicio) elif fecha_fin: queryset = queryset.filter(fecha__lte=fecha_fin) return queryset def ProspectoEditar(request, pk): prospecto = get_object_or_404(Prospecto, pk=pk) if request.method == 'POST': form = ProspectoForm(request.POST, instance=prospecto) if 'es_cliente' in request.POST: cliente = Cliente(nombre=prospecto.nombre) cliente.save() prospecto.es_cliente = True prospecto.delete() if form.is_valid(): form.save() return redirect('prospectos:prospectos_list') else: form = ProspectoForm(instance=prospecto) return render(request, 'prospectos-editar.html', {'form': form}) I try with this solution, adding delete() but it doesn't work class ProspectoListView(ListView): model = Prospecto template_name = 'prospectos.html' context_object_name = 'prospectos' def get_queryset(self): fecha_inicio … -
Failed to join room. Token authentication error
I am working on a django project in which I have used zeegocloud uikits for one-one video calling web application. Even when I am using the downloadable uikits html file provided by zeegocloud itself, in which it has generated token using appID, userID, serversecret, username, but then also token authentication error is coming. I am unable to solve this issue