Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
On click function is not working in script though models and views are ok and original template is working perfectly
In product_detail.html: {% extends 'partials/base.html'%} {%load static%} {% block content %} <style> /* Basic Styling */ html, body { height: 100%; width: 100%; margin: 0; font-family: 'Roboto', sans-serif; } .containerbox { max-width: 1200px; margin: 0 auto; padding: 15px; display: flex; } /* Columns */ .left-column { width: 65%; position: relative; } .right-column { width: 35%; margin-top: 60px; } /* Left Column */ .left-column img { width: 70%; position: absolute; left: 0; top: 0; opacity: 0; transition: all 0.3s ease; } .left-column img.active { opacity: 1; } /* Right Column */ /* Product Description */ .product-description { border-bottom: 1px solid #E1E8EE; margin-bottom: 20px; } .product-description span { font-size: 12px; color: #358ED7; letter-spacing: 1px; text-transform: uppercase; text-decoration: none; } .product-description h1 { font-weight: 300; font-size: 52px; color: #43484D; letter-spacing: -2px; } .product-description p { font-size: 16px; font-weight: 300; color: #86939E; line-height: 24px; } /* Product Configuration */ .product-color span, .cable-config span { font-size: 14px; font-weight: 400; color: #86939E; margin-bottom: 20px; display: inline-block; } /* Product Color */ .product-color { margin-bottom: 30px; } .color-choose div { display: inline-block; } .color-choose input[type="radio"] { display: none; } .color-choose input[type="radio"] + label span { display: inline-block; width: 40px; height: 40px; margin: -1px 4px 0 0; vertical-align: … -
why is this error coming after trying to deploy a django app on vercel?
After trying to deploy a django app on vercel, this error comes Running build in Washington, D.C., USA (East) – iad1 Cloning github.com/Anupam-Roy16/Web_project (Branch: main, Commit: 90df2f4) Cloning completed: 677.995ms Previous build cache not available Running "vercel build" Vercel CLI 33.5.3 WARN! Due to builds existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings Installing required dependencies... Failed to run "pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt" Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt ERROR: Ignored the following versions that require a different python version: 5.0 Requires-Python >=3.10; 5.0.1 Requires-Python >=3.10; 5.0.2 Requires-Python >=3.10; 5.0a1 Requires-Python >=3.10; 5.0b1 Requires-Python >=3.10; 5.0rc1 Requires-Python >=3.10 ERROR: Could not find a version that satisfies the requirement Django==5.0.2 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, … -
How can I use get_or_create in TranslatableModel?
I am using dajngo-parler to make my site multi-language. But I have a problem when querying. For example, in this query, only ID is created and the rest of the fields are not stored in the database. MyModel.objects.language('en').get_or_create(title='test',description='test') But when I use this method, there is no problem. MyModel.objects.language('en').create(title='test',description='test') Is there another way to create data in multi-language models with parler?? -
"ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS" in Django while using UNION function
I'm new to Django and want to use this snippet code in my project who use sqlite database: if "dashboard_filters_parent_checkbox" not in request.POST: all_task_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union( tasks_confirmed).values_list('id',flat=True) all_task_parent_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed).values_list('task_parent__id',flat=True) #.union(sub_tasks_no_confirmed) all_task_parent_id = list(set(all_task_id) & set(all_task_parent_id)) tasks_no_assign=tasks_no_assign.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_start=tasks_no_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_start=tasks_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_confirmed=tasks_no_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_confirmed=tasks_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) but I get this error when I open the page that above lines are in that code: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/Dashboard/ Django Version: 5.0.2 Python Version: 3.12.2 Installed Applications: ['django.contrib.ad...] Installed Middleware: ['django.middleware....] Traceback (most recent call last): File "C:\...\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\...\views\dashboard\dashboard.py", line 203, in Dashboard all_task_parent_id = list(set(all_task_id) & set(all_task_parent_id)) File "C:\...\Lib\site-packages\django\db\models\sql\compiler.py", line 1549, in execute_sql sql, params = self.as_sql() ^^^^^^^^^^^^^ File "C:\...\Lib\site-packages\django\db\models\sql\compiler.py", line 751, in as_sql result, params = self.get_combinator_sql( Exception Type: DatabaseError at /Dashboard/ Exception Value: ORDER BY not allowed in subqueries of compound statements. I search it and understand it's because "union" function and sqlite but don't now where is problem and didn't find any answer for fix it. what can I do and what's correct way? thanks in advance <3 -
Extra Square Brackets "[]" in Django Admin Login Page Rendering
please help me. I am using Django 5.0.2 and Python 3.12 with Apache 2.4 and mod_wsgi 5.0.0. When I run the development server, everything looks fine. However, when I run it on production over Apache, I encounter an issue where extra square brackets "[]" appear, as shown in the picture below: image1 : https://ibb.co/m6JXXDN This issue also appears in my forms: image2: https://ibb.co/ZV0Q3xN I have tried several solutions, but none have resolved the problem. Please help me. I checked the dependencies and the Apache configuration for static files. I also rechecked my forms and views. The app works perfectly on the local machine with the development server -
How to use cache system for large and dynamic data
I want to use a cache system for my django web application, I have been using django-cachepos for caching my data but now I have some issues like having big data for reports which includes a lot of filters and should be online when data upate . Now my response time is too long (like 12 13 s ) and I want some guides from you to implant a cache sytem or a cache strategy that can helps to improve my code cosider this that appliacation is going to be a large scale project and right now have 3 4 lead from all interner and cant stop being online Ps. I have this problem on some other endpoints with requests with lots of data I try to use redis functions to set and get data but I have no idea how to use it with filters and even cache response data -
how to open the poping window just bellow the burger logo in django
solve the JavaScript and CSS and html code with suitable reason of the code so that the Ui seems seamless and beautiful and attracting to interact to the user in the website. I am expecting the beautiful Ui of the window so that the Ui seems attracted and beautiful. -
Django JsonResponse returning 'Year and month parameters are required' despite parameters being present in request.GET
I am using 'fullcalendar' and I want to send the month and year to django view and fetch the total hours for each day in that month from this api: 'api/get_calendar_data/' to display the calendar properly. But then I am receiving an unexpected respond where it says it needs the parameters while there are present in the request. I will provide the code to and you will get what I am doing. dashboard.html: <div id="calendar"></div> <script src="{% static 'js/calendar.js' %}"></script> calendar.js: function updateCalendar(month, year) { console.log(year); console.log(month); $.ajax({ url: "/api/get_calendar_data/", // to my django view to fetch data method: "GET", data: { year: year, month: month }, // to django view to send month and year success: function (data) { // data = { '2024-02-01': 5, '2024-02-02': 7, ..} for (let date in data) { let hoursWorked = parseFloat(data[date]); let calendarDate = new Date(date); let formattedDate = calendarDate.toISOString().slice(0, 10); //to get the day number 2024-04-23 -> 23 let dayElement = calendarEl.querySelector( `[data-date="${formattedDate}"]` ); if (hoursWorked >= 7) { dayElement.style.backgroundColor = "#5cb85c"; //finished work } else { dayElement.style.backgroundColor = "#d9534f"; //not inished } } }, error: function (xhr, status, error) { console.error("Error fetching calendar data:", error); }, }); } //initialize the … -
Async Django MQTT Client cannot re-connect pg-pool after 24 hours
Let me tell you my structure and problem. I have sync and async containers on K8. These pods are running via this command in my docker-entrypoint.sh gunicorn myappname.wsgi:application --worker-class gevent --workers 3 --bind 0.0.0.0:8000. In the async ones, I run some MQTT Clients (paho.mqtt.client). This is my custom apps.py that runs clients asynchronously: import asyncio import importlib import sys from os import environ from django.apps import AppConfig, apps from django.db import connection from .server import MQTTConsumer # inherited from paho.mqtt.Client from .consumers import ResponseConsumer class CustomMqttConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'custom.mqtt' def ready(self): for _app in apps.app_configs.keys(): topic_patterns = [ ('$share/my-app/response', ResponseConsumer) ] connection.close() for _topic, _consumer in topic_patterns: asyncio.run(MQTTConsumer()(topic=_topic, consumer=_consumer)) Everything works perfectly until 24 hours passed after the first init of my consumers. After 24 hours, I get connection closed error for each MQTT request from my db (in this case pg-pool) BUT when I open a shell in my async container (docker exec -it <container_id> bash) and get in the django shell (python manage.py shell) I can use my models and filter my DB while my consumers throwing that error. I checked my pg-pool (show pool_processes) before and after restarting my async pods and saw that … -
Pydantic, Django Ninja "Day is out of range for month"
2024-02-29 14:04:15 pydantic.error_wrappers.ValidationError: 1 validation error for NinjaResponseSchema 2024-02-29 14:04:15 response 2024-02-29 14:04:15 day is out of range for month (type=value_error) I have fields "created_at" and "updated_at". Today my project crashed because of them. How can I update validators in schemas to skip those fields validation? I've tried multiple things but nothing helped me. My versions: django-ninja==0.22.0 pydantic==1.10.14 -
Based on two field input of a form need to generate choices for another field dynamically on Django
on _create_mywork_help.html ******************************* function generate_daily_time_list() { var start_time = document.getElementById("id_start_time").value; var interval = Number(document.getElementById("id_interval").value); var daily = document.getElementById("id_daily"); //document.getElementById("id_daily").value = document.getElementById("id_daily").defaultValue; document.getElementById("id_daily").innerHTML = ""; console.log(start_time); console.log(interval); console.log(daily); const stime = String(start_time).split(" "); const hm = stime[0].split(":"); console.log(hm[0]); console.log(hm[1]); var hr = Number(hm[0]); var mins = String(hm[1]); var pre = 0; while (hr > 0){ pre = hr; hr = hr - interval; } console.log(mins); console.log('Deba'); var i = pre; while (i < 24){ var option= document.createElement("option"); dtime = String(i).padStart(2, '0')+':'+mins; //dtime_v = 'x'+String(i).padStart(2, '0')+mins; console.log(dtime) i = i+interval; option.value= dtime; option.text= dtime; daily.add(option); } } class myworkAction(workflows.Action): start_time = forms.ChoiceField(label=_("Start Time"), required=False) interval = forms.CharField(label=_("Hourly"), required=False, initial=24, validators=[validate_scheduler_interval], widget=forms.TextInput( attrs={'placeholder': "Repeat interval must be in numbers only (Ex: 1 or 2)...", 'onkeyup': " $('#id_interval').val(document.getElementById('id_interval').value)", 'onchange': "generate_daily_time_list()"})) daily = forms.MultipleChoiceField(label=_("Daily"), required=False) class Meta: name = _("mywork") help_text_template = ("project/workloads/" "_create_mywork_help.html") def __init__(self, request, *args, **kwargs): super(myworkAction, self).__init__(request, *args, **kwargs) start_time_list = populate_time_list() self.fields['start_time'].choices = start_time_list I want to take input 12:15 PM start time and interval e.g. 2 It should generate choices for "daily" filed as e.g. like 14:15 , 16:15 and it is generating, but when i select and submitting it is giving error : Select a valid choice. 14:15 … -
Fly.io django and postgres deploy
I'm trying to deploy my django app in Fly.io with postgreSQL database, so I've followed de docs to attach my app with the postgres cluster with the main app. I’ve generated the DATABASE_URL like this: flyctl pg attach ac7-postgres Checking for existing attachments Registering attachment Creating database Creating user Postgres cluster ac7-postgres is now attached to ac7 The following secret was added to ac7: DATABASE_URL=postgres://ac7:@ac7-postgres.flycast:5432/ac7?sslmode=disable So I have this code in settings.py: os.environ['DATABASE_URL'] = 'postgres://ac7:<PASSWORD>@ac7-postgres.flycast:5432/ac7?sslmode=disable' DATABASES = { 'default': dj_database_url.config(default=os.getenv('DATABASE_URL')) } but when I try “py manage.py makemigrations” it shows: UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xe3 in position 76: invalid continuation byte Can someone help me? Please -
How can display values of item selected in dropdownlist all items from db in template django
Please help to get Revision and Company of selected Project in dropdownlist in software.html template django, image with more detail in attached, Thanks! models.py ` class PROJ(models.Model): User=get_user_model() author = models.ForeignKey(User, on_delete=models.CASCADE) project_id=models.CharField(max_length=100, null=True, blank=True, db_index=True) Company=models.CharField(max_length=100, null=True, blank=True) Revision=models.CharField(max_length=100, null=True, blank=True)` urls.py urlpatterns = [ path('software/', views.software, name='software'), views.py ` def software(request): assert isinstance(request, HttpRequest) PROJS = PROJ.objects.filter(author=request.user) return render( request, 'app/software.html', { 'year':datetime.now().year, 'PROJS': PROJS, } )` software.html ` <label class="col-md-3 col-form-label">Project/Site:</label> <div class="col-md-9"> <select class="form-select" name="Select" id="Select"> {% for PROJ in PROJS %} <option value="{{ PROJ.id }}">{{ PROJ.project_id }}</option> {% endfor %} </select> </div> <label class="col-md-3 col-form-label">Revision:</label> <div class="col-md-9"> <input type="text" class="form-control" name="Revision" placeholder="Revision" id="Revision" value="{{PROJ.Revision}}"> </div> <label class="col-md-3 col-form-label">Company:</label> <div class="col-md-9"> <input type="text" class="form-control" name="Company" placeholder="Company" id="Company" value="{{PROJ.Company}}"> </div>` descriptions -
"ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS" in Django while using UNION function [closed]
I'm new to Django and want to use this code: if "dashboard_filters_parent_checkbox" not in request.POST: all_task_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union( tasks_confirmed).values_list('id',flat=True) all_task_parent_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed).values_list('task_parent__id',flat=True) #.union(sub_tasks_no_confirmed) all_task_parent_id = list(set(all_task_id) & set(all_task_parent_id)) tasks_no_assign=tasks_no_assign.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_start=tasks_no_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_start=tasks_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_confirmed=tasks_no_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_confirmed=tasks_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) but I get this error: ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS I now this error shown for using Union function but where is problem? how can I do and what is correct way? thanks in advance <3 -
When I run "python .\manage.py runserver" I get this: No Python at '"C:\Users\Utilizador\AppData\Local\Programs\Python\Python312\python.exe'
virtual environment activated (env) PS C:\Users\Utilizador\Documents\FSapp> python .\manage.py runserver No Python at '"C:\Users\Utilizador\AppData\Local\Programs\Python\Python312\python.exe' virtual environment deactivated PS C:\Users\Utilizador\Documents\FSapp> python .\manage.py runserver python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 python .\manage.py runserver + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException When using "python3 .\manage.py runserver" I get python3 : The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 python3 .\manage.py runserver + CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException IMPORTANT: I'm using django and nodejs to build a full stack application I installed all the packages while having the virtual envirnmont "env" activated Here are my system variables Here are my users variables -
Filter a field in a form set (Django)
How to filter a field on a form so that items created by another user are not ordered I have a set of forms from django import forms from django.forms.models import inlineformset_factory from .models import Course, Module ModuleFormSet = inlineformset_factory(Course, Module, fields=['title', 'section', 'description'], extra=2, can_delete=True) In the form in the list of sections, sections created by another teacher appear. How to configure sections to be allocated only to the user who creates modules? How to write a field filter on a form? -
Making migrations for app models moved to another directory that's not their default creation directory
This is my folder structure backend server apps #directory I created endpoints #my app In settings.py INSTALLED_APPS[ ....... 'apps.endpoint' ] When I run python3 manage.py make migrations I'm receiving a ModuleNotFoundError: No module named 'endpoints' -
Django-allauth could not login existing user
I use Django 5 and django-allauth. Currently I do not use any advanced features of this library, the only reasons I use it: It has a well-developed workflow with email opt-in feature It can support both username and email based authentication out of the box. Here is my settings, related to the library: # django-allauth specific settings for regular accounts not including the social authentication part. ACCOUNT_AUTHENTICATION_METHOD="username_email" ACCOUNT_CHANGE_EMAIL=True ACCOUNT_CONFIRM_EMAIL_ON_GET=False ACCOUNT_EMAIL_REQUIRED=True ACCOUNT_EMAIL_VERIFICATION="mandatory" ACCOUNT_UNIQUE_EMAIL=True ACCOUNT_DEFAULT_HTTP_PROTOCOL="https" ACCOUNT_MAX_EMAIL_ADDRESSES=2 ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE=True ACCOUNT_LOGIN_ON_PASSWORD_RESET=True ACCOUNT_SESSION_REMEMBER=True ACCOUNT_USERNAME_REQUIRED=False ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE=False # Our specific signup and login forms with special styling ACCOUNT_FORMS = {'signup': 'user_profile.forms.CustomSignupForm', 'login': 'user_profile.forms.CustomLoginForm'} The only role of CustomLoginForm is to have customized css: from allauth.account.forms import LoginForm class CustomLoginForm(LoginForm): def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) # The parent class does similar. The only reason we had to make custom loginform # to handle bootstrap css self.fields["login"].widget.attrs.update({"class": TEXT_INPUT_CLASS}) if app_settings.AuthenticationMethod == AuthenticationMethod.USERNAME: self.fields["login"].widget.attrs.update({"placeholder": "Felhasználónév", "autocomplete": "username"}) elif app_settings.AuthenticationMethod == AuthenticationMethod.EMAIL: self.fields["login"].widget.attrs.update({"placeholder": "Email cím", "autocomplete": "email"}) else: self.fields["login"].widget.attrs.update({"placeholder": "Email cím / felhasználónév", "autocomplete": "email"}) self.fields["password"].widget.attrs.update({"class": TEXT_INPUT_CLASS, "placeholder": "Add meg a jelszavad", "autocomplete": "password"}) When I start my development server to see why I can not login with existing username and password, I used the Debug Toolbar to see SQLSs generated by … -
How to use utilize nested ArrayAgg in Django?
These are my models class TimeSheet(CommonModel): employee = models.ForeignKey( "employee.Employee", related_name="timesheets", on_delete=models.PROTECT ) project = models.ForeignKey( "core.Project", related_name="employee_timesheets", on_delete=models.PROTECT ) timesheet_date = models.DateField() clock_in_time = models.DateTimeField() clock_out_time = models.DateTimeField(null=True) class TimesheetEquipment(CommonModel): equipment = models.ForeignKey( "equipment.Equipment", on_delete=models.PROTECT, related_name="timesheet_equipments", ) resource_code = models.CharField(max_length=150) resource_name = models.CharField(max_length=511) rate = models.DecimalField( max_digits=30, decimal_places=decimal.ACCEPTED_DECIMAL_PLACE ) unit = models.CharField(max_length=63, default="Hour") timesheet = models.ForeignKey( "timesheet.Timesheet", on_delete=models.CASCADE, related_name="timesheet_equipments", ) equipment_attachments = models.ManyToManyField( "costcode.ResourceCode", related_name="timesheet_equipments", blank=True, through="timesheet.TimesheetEquipmentAttachment", help_text="Other Resources to be attached with this requirement", ) class TimesheetEquipmentAttachment(models.Model): timesheetequipment = models.ForeignKey( TimesheetEquipment, on_delete=models.CASCADE, related_name="timesheetequipmentattachments", ) resource = models.ForeignKey( "resource_management.CostSheetResource", related_name="timesheetequipmentattachments", on_delete=models.PROTECT, null=True, ) resource_code = models.CharField(max_length=150) resource_name = models.CharField(max_length=150) This is my queryset to get all the timesheet along with its equipments from django.db.models.functions import JSONObject from django.contrib.postgres.aggregates import ArrayAgg timesheets = ( TimeSheet.objects.filter(project_id=project_id, timesheet_date=date) .select_related("employee") .prefetch_related( "timesheet_equipments", "timesheet_equipments__timesheetequipmentattachments", ) .values("id") .annotate( timesheet_date=F("timesheet_date"), clock_in_time=F("clock_in_time"), clock_out_time=F("clock_out_time"), timesheet_equipments=ArrayAgg( JSONObject( equipment=F("timesheet_equipments__equipment_id"), equipment_name=F( "timesheet_equipments__equipment__equipment_name" ), resource_code=F("timesheet_equipments__resource_code"), resource_name=F("timesheet_equipments__resource_name"), rate=F("timesheet_equipments__rate"), unit=F("timesheet_equipments__unit"), ), distinct=True, ), ) .values( "id", "timesheet_date" "clock_in_time", "clock_out_time", "timesheet_equipments", ) .order_by("-timesheet_date") .distinct() ) this is the queryset that i am trying to get all the timesheets along with its all equipments and each equipments should have all of there equipment attachments if exists. But this did not worked. Any help would be highly … -
Issue with Celery Not Receiving Tasks - Django Ubuntu
I'm experiencing an issue with Celery where it doesn't respond automatically upon system boot. Here's a breakdown of my setup and the problem: Setup: Django project using Celery for asynchronous tasks. Celery workers configured with the @shared_task decorator. Using Redis as the broker with the CELERY_BROKER_URL set to 'redis://localhost'. Celery workers configured to run as a systemd service on Ubuntu. Problem: When the system boots up, Celery starts automatically, but asynchronous tasks are not executed. Manually starting Celery with the command home/ubuntu/.venv/bin/celery -A febiox.celery worker -l info -E works fine, and tasks are executed as expected. Checking the status of Celery service with sudo systemctl status celery.service shows that the service is active and running. However, when attempting to inspect active Celery nodes with celery -A febiox.celery inspect active, I get the error message Error: No nodes replied within time constraint. Interestingly, running the same command after manually starting Celery returns the expected result showing the correct node. Systemd Service Configuration: [Unit] Description=Celery Task Worker After=network.target [Service] Type=simple User=ubuntu WorkingDirectory=/home/ubuntu/febiox ExecStart=/home/ubuntu/.venv/bin/python3 /home/ubuntu/.venv/bin/celery -A febiox.celery worker -l info -E Restart=always StandardOutput=file:/var/log/celery/celery.log StandardError=file:/var/log/celery/celery_error.log [Install] WantedBy=multi-user.target Additional Information: Redis receives data when attempting to execute tasks. sudo systemctl reload celery.service doesn't produce any … -
"ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS" IN DJANGO WHILE USING UNION FUNCTION
I'm new to Django and want to use this code: if "dashboard_filters_parent_checkbox" not in request.POST: # all_task_id=[t.id for t in tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed)] #.union(sub_tasks_no_confirmed) # all_task_parent_id=[t.task_parent.id if t.task_parent and t.task_parent.id in all_task_id else 0 for t in tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed)] #.union(sub_tasks_no_confirmed) # all_tasks_children_id=[t.GetAllTaskChildrenId for t in tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed)] #.union(sub_tasks_no_confirmed) # all_tasks_children_id=[_id for id_set in all_tasks_children_id for _id in id_set ] all_task_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed).values_list('id',flat=True) #.union(sub_tasks_no_confirmed) all_task_parent_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed).values_list('task_parent__id',flat=True) #.union(sub_tasks_no_confirmed) all_task_parent_id = list(set(all_task_id) & set(all_task_parent_id)) # all_tasks_children_id=[t.GetAllTaskChildrenId for t in tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed)] #.union(sub_tasks_no_confirmed) # all_tasks_children_id=[_id for id_set in all_tasks_children_id for _id in id_set ] all_tasks_children_id = list(set(all_task_id) - set(all_task_parent_id)) tasks_no_assign=tasks_no_assign.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_start=tasks_no_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_start=tasks_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_confirmed=tasks_no_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_confirmed=tasks_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) but I get this error: ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS I now this error shown for using Union function but where is problem? how can I do and what is correct way? thanks in advance <3 but I get this error: ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS I now this error shown for using Union function but where is problem? how can I do and what is correct way? thanks in advance <3 -
Django Templates - should I place HTML tags inside blocks of text subject to translation?
Is there any way to simplify the translation process when I have phrases with links and other HTML elements in them ? Currently I am breaking long phrases into multiple translate tags which don't translate properly the meaning of the whole phrase: <span class="text-sm"> {% translate "Please" %} <a class="inline font-semibold cursor-pointer text-blue-600 border-b-2 border-transparent hover:border-b-2 hover:border-blue-600" href="{% url "shop:login" %}"> {% translate "login" %} </a> {% translate "to place your order. If you don’t have an account yet, you can" %} <a class="inline font-semibold cursor-pointer text-blue-600 border-b-2 border-transparent hover:border-b-2 hover:border-blue-600" href="{% url "shop:register" %}"> {% translate "register" %} </a> {% translate "here." %} </span> I have thought about using blocktrans, but this will carry the html tags into the .po file and maybe even translate the applied Tailwind CSS classes: <span class="text-sm"> {% blocktrans %} Please <a class="inline font-semibold cursor-pointer text-blue-600 border-b-2 border-transparent hover:border-b-2 hover:border-blue-600" href="{% url "shop:login" %}"> login </a> to place your order. If you don’t have an account yet, you can <a class="inline font-semibold cursor-pointer text-blue-600 border-b-2 border-transparent hover:border-b-2 hover:border-blue-600" href="{% url "shop:register" %}"> register </a> here. {% endblocktrans %} </span> Is there a way of doing this properly so that we can translate the whole … -
Update existing data by django-rest-framework upload file
I am able to add data normally, but cannot update existing data. I can add a new entry, but I can't update entries with the same name in the imported data. What should I do? class CategoryUploadView(APIView): authentication_classes = [OAuth2Authentication] permission_classes = [AllowAny] parser_classes = [MultiPartParser] def post(self, request): file_obj = request.FILES['file'] decoded_file = file_obj.read().decode('utf-8').splitlines() reader = csv.DictReader(decoded_file) for row in reader: serializer = CategorySerializer(data=row) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors, status=400) return Response({"message": "Data imported successfully"}, status=200) class CategorySerializer(serializers.ModelSerializer): class Meta: model=Category fields=['id', 'name'] def to_internal_value(self, data): data = data.copy() data['name'] = data.get('name', None).lower() return super().to_internal_value(data) class Category(models.Model): name = models.CharField(max_length=32, unique=True) description = models.CharField(max_length=255) update_on = models.DateField(auto_now=True) def __str__(self) -> str: return self.name -
Problem when doing a search with multiple results. NoReverseMatch
I am making a web application that uses the OpenLibrary API, using Django. In it I do a search within the API, if the results show more than one book, I get this error: NoReverseMatch at /search-results/ Reverse for 'book_detail' with arguments '('reina-roja-red-queen', 'Reina Roja / Red Queen')' not found. 1 pattern(s) tried: ['books/((?P[-a-zA-Z0-9_]+)/(?P[^/]+)+)'] My files are as follows: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("search-results/", views.search_results, name="search_results"), path("books/<slug:slug>/<str:title>", views.book_detail, name="book_detail"), ] views.py from django.shortcuts import render, get_object_or_404, redirect from django.utils.text import slugify from books.api_library import search_book_by_author, search_book_by_title from .models import Book import requests import json def index(request): """ Index page """ if request.method == "POST": type_search = request.POST.get("type_search") search = request.POST.get("search") if type_search == "title": books_data = search_book_by_title(search).get("docs", []) elif type_search == "author": books_data = search_book_by_author(search).get("docs", []) if not books_data: books_data = [] request.session['search_results'] = books_data return redirect('search_results') return render(request, "books/index.html") def search_results(request): """ View to display search results """ search_results = request.session.get('search_results', []) books = [] for book in search_results: slug = slugify(book.get("title", "")) book_info = { "title": book.get("title", ""), "author": book.get("author_name", ""), "isbn": book.get("isbn", ""), "cover": book.get("cover", ""), "publisher": book.get("publisher", ""), "cover_url": f"https://covers.openlibrary.org/b/id/{book.get('cover_i', '')}-S.jpg", "description": book.get("description", ""), "publish_date": … -
Django REST - Updating or Creating object with foreign key reference
Document is the parent Model and LineItem is the child model with a foreign key reference to Document I am able to delete LineItem individually. However, I am unable to create or update individual LineItem as I keep getting a ValidationError stating 'document': [ErrorDetail(string='This field is required.', code='required') I have found a few workarounds but am wondering if there is a more standard way to solve this that I maybe overlooking class Document(models.Model): """ ORM representing Document object """ id = models.AutoField( primary_key=True, ) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='documents', ) class LineItem(models.Model): """ ORM representing line items in a document. """ id = models.AutoField( primary_key=True, ) document = models.ForeignKey( Document, on_delete=models.CASCADE, related_name='line_items', ) description = models.CharField( max_length=50, blank=True, db_default='', default='', ) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='line_items', ) serializers.py class LineItemSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = LineItem fields = '__all__' urls.py # Add a document line item path('api/document/<int:doc_pk>/line/', DocumentLineItemCreateAPI.as_view(), name='document-line-item-add-api'), # Edit a document line item path('api/document/<int:doc_pk>/line/<int:pk>/', DocumentLineItemUpdateAPI.as_view(), name='document-line-item-update-api'), views.py class DocumentLineItemUpdateAPI(generics.RetrieveUpdateDestroyAPIView): """ Unified view for retreiving, updating or deleting document line items """ serializer_class = LineItemSerializer def get_queryset(self): return LineItem.objects.all() def get_object(self): obj = get_object_or_404(self.get_queryset(), \ document_id=self.kwargs.get('doc_pk'), id=self.kwargs.get('pk')) return obj def destroy(self, request, doc_pk, pk, *args, …