Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Reverse for '' not found. '' is not a valid view function or pattern name
I am getting an error "Django Reverse for '' not found. '' is not a valid view function or pattern name.". I was searching for a way to fix this but couldn't find anything the urls.py and views.py, home.html and atrakcja_details.html are in the same App the same folder. urls.py: from django.urls import path from . import views urlpatterns = [ path('atrakcja_details/int:atrakcja_id/', views.atrakcja_details, name='atrakcja_details'), path('about/', views.about_page, name='about'), ] views.py: from django.shortcuts import render, get_object_or_404 from .models import Atrakcja from django.http import HttpResponse def atrakcja_details(request, atrakcja_id): # Add atrakcja_id parameter if atrakcja_id: atrakcja = get_object_or_404(Atrakcja, id=atrakcja_id) return render(request, 'atrakcja_details.html', {'atrakcja': atrakcja}) else: return HttpResponse("Atrakcja not found.") def about_page(request): return render(request, 'about/about.html') home.html: I tried everything but it still doesnt work:(( please help me -
Django form saving wrong information to database
So in my form, when I select a time choice, for example "8 PM" it stores in the database as a different time, I've checked the form submission and it is being submitted as the correct time, but not being saved as such, is there anything wrong with the code? from django.core.exceptions import ValidationError from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now from django.core.validators import MinValueValidator, MaxValueValidator class Booking(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) special_occasion = models.CharField(max_length=11, choices=[('None', 'None'), ('anniversary', 'Anniversary'), ('date', 'Date'), ('business', 'Business')]) meal_day = models.DateField() number_of_guests = models.PositiveIntegerField( null=True, validators=[MinValueValidator(1), MaxValueValidator(6)] ) customer_name = models.CharField(max_length=50) TIME_CHOICES = [ ('13:00', '01:00 PM'), ('14:00', '02:00 PM'), ('15:00', '03:00 PM'), ('16:00', '04:00 PM'), ('17:00', '05:00 PM'), ('18:00', '06:00 PM'), ('19:00', '07:00 PM'), ('20:00', '08:00 PM'), ] meal_time = models.CharField(max_length=5, choices=TIME_CHOICES) def clean(self): if self.meal_day and self.meal_day < now().date(): raise ValidationError("Cannot make a booking in the past.") existing_bookings = Booking.objects.filter(meal_time=self.meal_time, meal_day=self.meal_day) if self.pk: existing_bookings = existing_bookings.exclude(pk=self.pk) if existing_bookings.exists(): raise ValidationError("A booking already exists at this time on this day.") super().clean() # Call parent's clean method for remaining validations def save(self, *args, **kwargs): if not self.pk: available_times = [choice[0] for choice in self.TIME_CHOICES] booked_times = Booking.objects.filter(meal_day=self.meal_day).values_list('meal_time', flat=True) available_times = … -
KeyError: '__reduce_cython__' when trying to import sklearn package into Django app
When attempting to run my Django app with python manage.py runserver, I am getting the following error relating to a scikit-learn module import: File "sklearn\\metrics\\_pairwise_distances_reduction\\_argkmin.pyx", line 1, in init sklearn.metrics._pairwise_distances_reduction._argkmin KeyError: '__reduce_cython__' This is the last line in a larger error message, listed below. I have tried everything I've found online, including: upgrading all packages uninstalling and reinstalling related packages checking package dependencies are satisfied using pipdeptree to ensure package versions aren't conflicting restarting vscode, laptop etc. Despite this, every time I run python manage.py runserver I get the same error appearing. I'm using pip to install packages. Here are my current package versions in this venv: |asgiref |3.7.2| |Cython |3.0.10| |Django |5.0.5| |django-cors-headers |4.3.1| |django-environ |0.11.2| |djangorestframework |3.14.0| |joblib |1.4.2| |numpy |1.26.4| |packaging |24.0| |pandas |2.2.1| |pip |24.0| |pipdeptree |2.19.1| |psycopg |3.1.18| |psycopg2-binary |2.9.9| |python-dateutil |2.9.0.post0| |pytz |2024.1| |scikit-learn |1.4.2| |scipy |1.13.0| |six |1.16.0| |sqlparse |0.4.4| |stringcase |1.2.0| |threadpoolctl |3.5.0| |typing_extensions |4.9.0| |tzdata |2024.1| Interestingly from sklearn.feature_extraction.text import TfidfVectorizer causes no issues, but from sklearn.metrics.pairwise import cosine_distances is the line causing the issue. Please help! Have been stuck on this for a few days now. Full error message: Exception in thread django-main-thread: Traceback (most recent call last): File "C:userpath\AppData\Local\Programs\Python\Python312\Lib\threading.py", … -
Page not found (404) appears when performing tutorial
I get the following error after many tries Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. The code is written as follows, as shown in the tutorial mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls", include("polls.urls")), path("admin/", admin.site.urls), ] polls/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] polls/views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") mysite/setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] I asked questions to chatGPT and Llama3 and they told me to ask them here. Repeatedly restarting the server and copying and pasting the code did not solve the problem. Cache removal and re-installation of Python, Django, and virtual environments have also been performed. Let me know if there is anything else I should check. -
How do I customize Djoser endpoint '/users/me/' to return all custom user fields?
from djoser.serializers import UserCreateSerializer, UserSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserSerializer(UserSerializer): class Meta(UserSerializer.Meta): model = User fields = ('id','email','name','phone_number','address') The endpoint only returns id, email and name. I want it to return all other fields. -
How to display dropdown menu in javascript
I'm using a javascript to display a table in a django template. If the receipt's is_disbursed value is True and the paid_status is Settled, I want the dropdown menu to contain Print only. If is_disbursed is False and the paid_status is Settled, it should display the Print, Disburse and the Reverse options. If is_disbursed is True and paid_status is Partially Paid, I want to display the Print, Collect Balance, and the Reverse options. If is_disbursed is False and the paid_status is Unpaid, the dropdown should contain Print, Collect Balance, and Reverse #html <div class="card-body"> <div id="table-receipts" data-rent-receipt-url="{% url 'agency_rent_receipt' pk='PLACEHOLDER' %}" data-disburse-rent-url="{% url 'disburse_rent' pk='PLACEHOLDER' %}" data-rent-bal-url="{% url 'rent_balance' receipt_id='PLACEHOLDER' %}"></div> </div //js <script> document.addEventListener("DOMContentLoaded", function () { const table = document.getElementById("table-receipts"); if (table) { const printReceiptUrl = table.getAttribute("data-rent-receipt-url"); const rentDisbursementUrl = table.getAttribute("data-disburse-rent-url"); const rentBalanceUrl = table.getAttribute("data-rent-bal-url"); fetch('/accounting/receipts_data/api') .then(response => response.json()) .then(receipt_data => { new gridjs.Grid({ columns: [ { name: "Receipt Number", width: "180px" }, { name: "Date", width: "120px" }, { name: "Address", width: "120px" }, { name: "Tenant", width: "120px" }, { name: "Status", width: "120px" }, { name: "Action", width: "100px", formatter: function (cell, row) { const receiptId = row.cells[5].data; const finalprintReceiptUrl = printReceiptUrl.replace('PLACEHOLDER', receiptId); const finalrentDisbursementUrl … -
Django 4.2 how to display deleted object failure in modeladmin page?
Code used to override the delete_queryset in the modeladmin: def get_actions(self, request): actions = super().get_actions(request) del actions['delete_selected'] return actions def really_delete_selected(self, request, queryset): ''' # 1. Update the group-mailbox relation: `goto` values if mailbox(es) are deleted # 2. Sending a mail to the current user with CSV of mailboxes deleted # 3. Used domain space will reduce by the maxquota of mailbox ''' response = None print('delete from mailbox queryset called') try: mbox_list = [] failed_deletions = [] print(queryset) for obj in queryset: mdomain = None # COMPLETE MAILBOX DELETION OF FOLDERS, DOVECOT ENTRY, ADMIN PANEL PERMANENTLY api_delete_status = call_purge_mailbox_api(request,obj) response = api_delete_status print('response---------',response, response['status_code']) if response['status_code'] == 200: # Set the quota value after deletion of mailbox(es) mdomain = Domain.objects.get(id=obj.domain.pk) mdomain.quota -= obj.maxquota mdomain.save() mbox_list.append(obj.email) # Remove the user from the group mailing lists # master_grp_list = GroupMailIds.objects.exclude(goto=None) removed_from_groups :bool = remove_from_group_lists(obj.email,mbox_list) print('mailbox deletion completed.....') # TODO: List for sending a mail to the currently logged in user with CSV of # mailboxes deleted else: print('Failed to delete mailbox:', obj.email) failed_deletions.append(obj.email) print(failed_deletions, len(failed_deletions)) if mbox_list: # Check if any mailboxes were successfully deleted self.message_user(request, f"Successfully deleted {len(mbox_list)} mailbox(es).",level='success') for email in failed_deletions: # Display error message for each failed … -
I want to convert the python data structure into yaml format
@require_http_methods(["POST"]) @csrf_exempt @api_view(['POST']) @permission_classes([IsAuthenticated]) def SetAlertRules(request): try: if not request.body: return Response({'error': "Data for setting alert not provided"}, status=http_status.HTTP_400_BAD_REQUEST) payload = json.loads(request.body) if not payload: return Response({'error': "Data for setting alert not provided"}, status=http_status.HTTP_400_BAD_REQUEST) vm = payload.get('vm') connector = payload.get('connector') panel = payload.get('panel') threshold = payload.get('threshold') notification_channel = payload.get('notification_channel') # for now, we are only focusing on email user = payload.get('user') # user will be the email id if not vm or not connector or not panel or not threshold or not notification_channel or not user: return Response({'error': "Required data for setting alert not provided"}, status=http_status.HTTP_400_BAD_REQUEST) # establish a ssh connection with the vm ssh=None try: username="" password="" vault_path = f'secret/{str(vm).strip()}' response= read_vault_data(vault_path) status_code = response.status_code data = response.data if status_code == 200: username = data['username'] password = data['password'] ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(vm, username=username, password=password) sftp = ssh.open_sftp() # --------- START -> Alert addition in prometheus rules.yml file ----------- ######### # checking if prometheus_rules.yml file is present or not, if yes, then appending the alert rule/s, else creating and adding alert rule/s prometheus_rules_config_path = '/usr/APM/script_data/prometheus-2.44.0.linux-amd64/prometheus_rules.yml' # to check if file exists, of not create it try: sftp.stat(prometheus_rules_config_path) except FileNotFoundError: log_info(f"prometheus_rules.yml is created now----") ssh.exec_command("sudo touch /usr/APM/script_data/prometheus-2.44.0.linux-amd64/prometheus_rules.yml") stdin, stdout, stderr … -
how to add email sending port to the security group in AWS ec2 instance
I'm trying to send an email from my back end that is hosted on an ec2 instance on amazon web services , but the function that runs this part takes a very long time to start the request that it gives me back a timeout error , so i think i need to add the port in the security group but am not aware how to set this up !! here is how my email server settings looks like : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.bizmail.yahoo.com' EMAIL_USE_TLS = True EMAIL_PORT = 465 EMAIL_HOST_USER = "my email here" EMAIL_HOST_PASSWORD = "my password here" -
Validation error doesn't render on the template with 2 form
I have in my template with a form in which data is collected in 2 Django forms but sent to the view in the same post like this: <form> {{ form1 }} {{ form2 }} </form> The data is collected in the view and validated. To validate, I have validations declared in both forms. In case the validations fail because the data is incorrect, they return a raise (depending on which one or ones have failed). This raise is what should be shown on the screen to the user as an error. If the failed validation is in the second form, it displays the error correctly and without problems. Now, in the case that the failure is in the first form, the page simply reloads and does not show the error. The data already entered in the form is not lost and can be corrected, but the error is not displayed. My view is something like this: def create(request): form1 = Form1(request.POST or None) form2 = formset_factory(Form2, extra=0) form2Set = form2(request.POST or None, prefix='participant') context = { 'form1': form1, 'form2Set': form2Set, } if request.method == 'POST': if form1.is_valid() and form2Set.is_valid(): # Logic else: context['form1'] = form1 context['form2Set'] = form2Set return … -
Django + Celery logging configuration on Heroku
TLDR; I deployed a django + celery app on heroku but I'm unable to see Celery logs on heroku logs. django==5.0.1 celery==5.3.4 Here are the relevant files Procfile web: daphne ecom_proj.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: celery -A ecom_proj.celery_app worker -E -B --loglevel=INFO settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "base": { "()": "django.utils.log.ServerFormatter", "format": "[{server_time}] {name} {levelname} {module} {message}", "style": "{", } }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "base", "level": "INFO", }, }, "loggers": { "": { "handlers": ["console"], "level": "INFO", }, "django": { "handlers": ["console"], "level": "INFO", "propagate": False, }, "celery": { "handlers": ["console"], "level": "INFO", "propagate": False, }, }, } celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecom_proj.settings") celery_app = Celery("ecom_proj_celery") celery_app.autodiscover_tasks() myapp/tasks.py import logging from celery import shared_task logger = logging.getLogger(__name__) @shared_task def my_task(): logger.info("task has started") # Do something.... With all these files, I deploed the django project on heroku and able to see web process's log messages however for worker process (Celery), I can't see any logs that are in task functions. although I'm able to see all celery logs on local machine with same configuration. I went through different SOF questions and most of them are … -
Ordering in the Django admin by related manytomany field
This is my models.py: class Person(models.Model): surname = models.CharField(max_length=100, blank=True, null=True) forename = models.CharField(max_length=100, blank=True, null=True) class PersonRole(models.Model): ROLE_CHOICES = [ ("Principal investigator", "Principal investigator"), [...] ] project = models.ForeignKey('Project', on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) person_role = models.CharField(choices=ROLE_CHOICES, max_length=30) class Project(models.Model): title = models.CharField(max_length=200) person = models.ManyToManyField(Person, through=PersonRole) @admin.display(description='Principal investigator') def get_PI(self): return [p for p in self.person.filter(personrole__person_role__contains="Principal investigator")] I would like to order the column of 'principal investigator' in the django Admin backend for the projects page. How can I do that? This is my attempt, which is not working: admin.py class ProjectAdmin(ImportExportModelAdmin): ordering = ('title','get_principal_investigator') def get_principal_investigator(self, obj): return self.get_PI get_principal_investigator.admin_order_field = "get_PI" get_principal_investigator.short_description = "Principal investigator" -
When i try to display on front-end the variavel "face_names" he always come empty
I have a facial recognition webapp in django, and I'm trying to show the user through a variable "face_names" which names are being captured on the screen, but it is always empty even when it has values inside. I've already tried just putting the value, you always have to search for a different value and it still didn't work, I just wanted to show it in text form. Views.py class FaceRecognition: ... def run_recognition(self, request, frame): ... response_data = { "face_names": face_names, } print("response_data:", response_data) # Vamos retornar esse dicionário. return JsonResponse (response_data) HTML <h1 class="titulo">Camera</h1> <div id="error-message" style="display: none;"> <p>Error aaccessing Camera </p> </div> <video id="video" autoplay></video> <canvas id="canvas" width="640" height="480" style="display: none;"></canvas> <div id="processing-message" style="display: none;">Running</div> <div id="face-names"></div> <button id="capture-button" onclick="captureFrame()">Capture Frame</button> JavaScript function sendFrameToServer(blob) { showProcessingMessage(); hideButton(); const data = new FormData(); data.append('frame_data', blob, 'frame.jpg'); fetch('/processar_reconhecimento_facial/', { method: 'POST', headers: { 'X-CSRFToken': getCookie('csrftoken') // Adicione o token CSRF }, body: data }).then(response => { if (response.ok) { // Se a resposta for bem-sucedida, capture o próximo frame console.log(response); captureFrame(); } if (response.headers.get('Content-Type') === 'application/json') { console.log("json response"); console.log(data); return response.json(); } else { console.log("blob response"); return response.blob(); } }) .then(data => { if (data.message === 'redirecionamento') { … -
How to access attribute of a foreign key model inside serializer django rest framework?
I have two models named Market, Exchange class Exchange(models.Model): name = models.CharField(max_length=20) class Market(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) price = models.FloatField(default=0.0) What I need to do is get name field in Exchange Model inside MarketSerializer -> class MarketSerializer(serializers.ModelSerializer): class Meta: model = Market fields = ('exchange_name', 'price', ) How can I do that? -
Django Project Stuck at Login Page
I'm very new to Django and I am trying to create an booking website. I want that after login it should redirect to my booking.html page, but instead, I had this login page always keep heading back to login page over and over again This is my login.html : {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/signin.css' %}"> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Bootstrap Bundle with Popper --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script> <div class="row justify-content-center"> <div class="col-md-4"> <div class="login-container"> {% if session.success %} <div class="alert alert-success alert-dismissible fade show" role="alert"> {{ session.success }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} {% if session.loginError %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> {{ session.loginError }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} <div class="row justify-content-center"> <div class="wow fadeInUp" data-wow-delay="0.1s"> <main class="form-signin"> <div class="wrapper"> <div class="logo"> <img src="{% static 'img/logo.png' %}"> </div> <br> <div class="text-center mt-4 name"> Login Dulu Yuk </div> <br> <form id="loginForm" action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="p-3 mt-3"> <div class="form-floating form-field d-flex align-items-center"> <input type="text" name="username" class="form-control rounded {% if form.errors.username %}is-invalid{% endif %}" id="username" placeholder="Username" autofocus required> <label for="username">Username</label> {% if … -
django - is UniqueConstraint with multi fields has same effect as Index with same field?
I wrote a django model that you can see below, I want to know having the UniqueConstraint is enough for Search and Selecting row base on user and soical type or I need to add the Index for them. if yes what is the different between them becuse base on my search the UniqueConstraint create an Unique Index on DB like posgresql. model: class SocialAccount(Model): """Social account of users""" added_at: datetime = DateTimeField(verbose_name=_("Added At"), auto_now_add=True) user = ForeignKey( to=User, verbose_name=_("User"), db_index=True, related_name="socials", ) type = PositiveSmallIntegerField( verbose_name=_("Type"), choices=SocialAcountType, ) class Meta: constraints = UniqueConstraint( # Unique: Each User Has Only one Social Account per Type fields=( "user", "type", ), name="user_social_unique", ) # TODO: check the UniqueConstraints is enough for index or not indexes = ( Index( # Create Index based on `user`+`type` to scan faster fields=( "user", "type", ), name="user_social_index", ), ) base on the above description I searched but I can't find any proper document to find how django act and we need extra index for them if they are a unique togher already? Note: I know there are some other questions that are similar but they can't answer my question exactly -
Error on calling .delete and update methods django
I have a stage model defined as below. When I try to perform delete operation I am getting below error. For other models, delete is working fine. previously I have been using django 2.2. After Upgrade I am seeing this error. from djangodeletes.softdeletes import ( SoftDeletable, SoftDeleteManager, SoftDeleteQuerySet, ) class Stage(SoftDeletable, models.Model): name = models.CharField(max_length=50) stage_type = models.CharField( choices=STAGE_TYPE_CHOICES, null=True, blank=True, max_length=50, ) close_stage_type = models.CharField( choices=CLOSE_STAGE_TYPE, null=True, blank=True, max_length=20, ) sequence = models.IntegerField(null=True, blank=True) pipeline = models.ForeignKey( Pipeline, null=True, blank=True, on_delete=models.CASCADE, related_name="pipeline_stages", ) created_by = models.ForeignKey( "accounts.User", on_delete=models.SET_NULL, null=True, related_name="stage_created_by", ) modified_by = models.ForeignKey( "accounts.User", on_delete=models.SET_NULL, null=True, related_name="stage_modified_by", ) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) objects = SoftDeleteManager.from_queryset(SoftDeleteQuerySet)() def __str__(self): return str(self.id) Stage.objects.get(id = 1240).delete() File "/home/srinivas/design_studio_app_1/design_studio_app/prac.py", line 50, in <module> stage.delete() File "/home/srinivas/design_studio_app_1/.venv/lib/python3.8/site-packages/djangodeletes/softdeletes/models.py", line 78, in delete for (field, value), instances in instances_for_fieldvalues.items(): AttributeError: 'list' object has no attribute 'items'``` I am using below versions Python 3.8.18, Django 4.2.9, djangodeletes 0.43 what could be the issue? -
What is the best approach to preserve GET parameters in django?
I have a ListView which I display using HTML <table> element. Each column is a field on model, while each row is a particular model instance. For this view I implemented search over multiple model fields (via GET form with query parameter search), filtering for each model field (via GET forms with query parameters filter--{{ field.name }}-{{ filter-type }}) and ordering over multiple fields (via query parameter order). I am planning to add pagination and ability for user to set page size (so soon two more query parameters). My question is: is there a simple approach to handle preserving existing unchanged GET values in both anchors and GET forms? For context: All three can be active at the same time, so paths can look like all of: /example/ /example/?filter--service_expires_at-datetime_from=2024-02-27T09%3A31&filter--service_expires_at-datetime_to= /example/?filter--username-icontains=abc&search=test /example/?order=-username,service_expires_at&search=test&filter--username-icontains=abc Search and filters have both links (to clear search or particular filter) and GET forms (to set search or particular filter). Order has links, which modify order GET parameter to either add ASC or DESC sort (or remove both) over particular column. My problem is that preserving GET parameters got quite cumbersome - for example, when I want to change order value, I need to take care to preserve … -
(Error) OSError: (WinError 6) The handle is invalid, when running python manage.py shell, I do not understand what is happening?
models.py file # Create your models here. class Flight(models.Model): origin = models.CharField(max_length=64) destination = models.CharField(max_length=64) duration = models.IntegerField(null=False) Then I run python manage.py shell in terminal python manage.py shell Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 8.12.3 -- An enhanced Interactive Python. Type '?' for help. In [1]: from flights.models import Flight Cancelling an overlapped future failed future: <_OverlappedFuture pending overlapped=<pending, 0x1af989b8430> cb=[BaseProactorEventLoop._loop_self_reading()]> Traceback (most recent call last): File "C:\Users\jaina\AppData\Local\Programs\Python\Python38\lib\asyncio\windows_events.py", line 66, in _cancel_overlapped self._ov.cancel() OSError: [WinError 6] The handle is invalid Above error happens, How can I resolve this, please help. -
In my template i'm trying to hide alert massage div if the notification item is None
{% if not notfication in alert %} <div style=" background: no-repeat; "> <div class=""> <span>None</span> </div> </div> {% else %} <div class="marquee-area"> <div class="marquee-wrap"> {% for notfication in alert %} <span>{{ notfication.title }}</span> {% endfor %} </div> </div> {% endif %} When I try to test it, regardless of whether there is data or not, I get Nothing her text -
Can anyone help me to reach out Lead Python Developer
I have been looking candidates with 8+ years of experience with 5+ core Python Developer and AI/ML experience too. I have used Github, Naukri, and LinkedIn, but I'm struggling to find the right candidate. Can you suggest a better way to target people with specific domain, role, or software experience? 6 years of experience, 5+ years in bringing to life web applications, mobile applications, and machine learning frameworks. Hands on work experience with: Python, R, Django, Flask, JavaScript (ES6), React, Node.js, MongoDB, Elasticsearch, Azure, Docker, Kubernetes, Microservices Good knowledge of caching technologies like Redis and queues like Kafka, SQS, MQ etc. Knowledge of Big Data, Hadoop would be a plus -
Package Django app without moving it to an external folder
We are working in a Django project with many applications. Our idea is to package them individually to use in other projects (like plugins). Is there any way to package an application without moving it to an external folder (like documentation explains)? We tried to add a setup.py file inside app folder and run python setup.py sdist. The command creates the dist/ and .egg-info/ folders, but then when we install the tar.gz in a new Django project using pip, it seems that the package itself is not installed, but only the .egg-info folder. Our current folder structure is: project/ app/ __init__.py admin.py apps.py models.py serializers.py setup.py tests.py urls.py views.py ... manage.py requirements.txt -
Combine and sum hours user spent per day
I am trying to sum all hours the user spent per day. I used this line of code: from django.db.models import F, Sum from django.db.models.functions import TruncDate Clocking.objects.filter(clockout__isnull=False, user=nid).values(date=TruncDate('clockin')).annotate(total=Sum(F('clockout') - F('clockin'))).order_by('clockin')) I have this result which calculates the hours into seconds. But if the user is clocking n times per day, how can I sum those hours or seconds in one date? <QuerySet [{'date': datetime.date(2024, 5, 7), 'total': datetime.timedelta(seconds=14418)}, {'date': datetime.date(2024, 5, 7), 'total': datetime.timedelta(seconds=9)}, {'date': datetime.date(2024, 5, 8), 'total': datetime.timedelta(seconds=9)}, {'date': datetime.date(2024, 5, 8), 'total': datetime.timedelta(seconds=3609)}]> -
Django `db_table` not renaming table
This question is (surprisingly) unlike similar ones, which ask about doing this dynamically, or ask how to do it in the first place. This question regards those suggestions not working as expected. Brief summary of situation: We made a series of Django apps as part of an API used in a real web app. We named those apps in ways that made sense at the time, e.g., "organizations" and "authentication". Now, we are packaging these apps as a distributable library, so a third party can install our apps in their API. The client already has apps named "organizations" and "authentication", causing conflicts (because Django apps must have unique names). Because we are creating the reusable library, we are renaming our apps from organizations to mycompany_organizations with corresponding model renames from Organization to MyCompanyOrganization to make them unique and distinguishable. I have made a series of migrations following this guide to create a new app and move the models over without losing data. Everything worked until someone added a new app that referenced our Organization (now named MyCompanyOrganization) model. This migration results in relation my_company_orgaanization does not exist, despite multiple foreign keys already pointing to my_company_organizations.organization and working fine. I inspected … -
Django: ModuleNotFoundError: No module named 'dotenv'
I see hundreds with this issue, but the answers to other posts aren't working for me. I'm simply trying to use dotenv and an .env file to hide sensitive data like an email password. I've tried this and it didn't work: pip uninstall dotenv pip uninstall python-dotenv pip install python-dotenv Error Traceback: Traceback (most recent call last): File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\core\management\commands\runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _ gcd_import File "<frozen importlib._bootstrap>", line 1007, in _ find_and_load File "<frozen importlib._bootstrap>", line 986, in _ find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _ load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _ call_with_frames_removed File "C:\Users\mattk\Box\WeConsent\VoterSay10\settings.py", line 14, in <module> import dotenv ModuleNotFoundError: No module named 'dotenv' from settings.py: import dotenv from dotenv import load_dotenv