Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
{'sales@mydomain.co': (553, b'5.7.1 <abc@gmail.com>: Sender address rejected: not owned by user sales@mydomain.co')}
I have a contact form on my website where users fill in their name, email and message to contact support which in this case is sales@mydomain.co and say the sender's email is abc@gmail.com. When a user submits the form, the form yields an error {'sales@mydomain.co': (553, b'5.7.1 <abc@gmail.com>: Sender address rejected: not owned by user sales@mydomain.co')} The form works if the sender's email belongs to the organization sales@mydomain.co. Is it possible to for a user to send an email(using a different organization email, such as Gmail) through the online form? here is my forms.py class ContactForm(forms.Form): name = forms.CharField(label='Your name', max_length=100) email = forms.EmailField(label='Your email', max_length=100) message = forms.CharField(max_length=600, widget=forms.Textarea) def send_mail(self): logger.info("Sending email to customer service") subject = "Site message" message = f"From: {self.cleaned_data['name']} <{self.cleaned_data['email']}>\n{self.cleaned_data['message']}" sender_email = self.cleaned_data['email'] # Use the user's email as the sender recipient_list = ['sales@mydomain.co'] # My domain email address send_mail( subject, message, sender_email, recipient_list, fail_silently=False, ) -
Attempting to migrate an Django ImageField, but failing to migrate
I am currently facing a problem with trying to migrate a Django Image field from a folder named media_root located inside a folder named static_cdn inside of my current project here is what my current file structure looks like as that may help; veganetworkmain -----profiles -------static_cdn ---------media_root ----------test.png Test.png is a png file that is generated using a picture generation algorithm using Pillow, here is what Test.png actually looks like: However what actually happens when I try to implement the code to get the picture into my program using a Django Image Field is that it just becomes white as seen here: I had tried methods like using python manage.py makemigrations, python manage.py migrate, changing the static by changing url_patterns and setting and even python ./manage.py makemigrations profiles. Here are the links to each method that I had tried: Django - makemigrations - No changes detected Page not found 404 Django media files And finally here is my code that I am currently working with during this time: models.py from django.db import models from django.shortcuts import reverse from django.contrib.auth.models import User from .utils import get_random_word from django.template.defaultfilters import slugify from django.db.models import Q -------------------------------------------------- class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) … -
400 Bad Request Error in an application using Django, Gunicorn, and Nginx
I've been trying to troubleshoot my issue with no success for a while now, so I hope posting here helps. I am developing an application using Django REST Framework, Gunicorn, and Nginx. The idea is to have Gunicorn serve the Django applicaiton, and have Nginx be used as a reverse proxy that holds the SSL certs. I've referenced multiple guides on hosting applications using these three technologies, with little success. I have my Django application connected to gunicorn using a sock file on port 80, and my Nginx server blocks listen for both port 80 and 433 (for SSL purposes). I have tried just about everything I can think of, and yet I am still getting a 400 - Bad Request error whenever I navigate to the domain that should serve the API. This is my Nginx sites-available file, with just a couple of names changed for security purposes: server { listen 80; server_name www.querymarketplace.net; return 301 http://querymarketplaceapi.net$request_uri; } server { listen 80; server_name querymarketplaceapi.net 157.245.10.103; location /static/ { root /home/jbisc/qm_marketplace/; } location / { include proxy_params; proxy_pass http://unix:/home/jbisc/qm_marketplace.sock; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; } } server { listen 443 ssl; listen [::]:443 ssl; # Optional: … -
How do I pass a Javascript variable to my Django framework to be used in template or via get_context?
I have been working to pass form values to a modal using Django. I have gotten most of the way there, but I can't quite make out how to connect the two.... Here is my AJAX... $("#avail").on("click", function(event) { var modalavail = document.getElementById("myModalavail"); var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); event.preventDefault(); $(window).unbind('beforeunload'); $.ajax({ method: 'get', headers: { "X-CSRFToken": token }, url: "", processData: false, contentType: false, cache: false, enctype: 'multipart/form-data', success: function(resp) { modalavail.style.display = "block"; for (var checkbox of markedCheckbox) { console.log(checkbox.value + ' '); } }, error: function (request, status, error) { console.log(request.responseText); showAjaxFormErrors(JSON.parse(request.responseText)); $('html, body').animate({ scrollTop: 0 }, 50); }, }); }); Here is my HTML... <button class="button209" id="avail">Check Availability</button> <div id="myModalavail" class="modal"> <div class="modal-content"> <span class="close"></span> <img class="logo4" src="/static/images/threecircles.svg"> <div class="table56"> {% for entry in form.approvers %} <table class="table57"> <thead> <tr> <th class="title156">Name</th> <th class="title118">Available?</th> </tr> </thead> <tbody> <tr> <td class="title156">{{ entry.name }}</td> <td class="title117">Yes</td> </tr> </tbody> </table> {% endfor %} </div> <input type="hidden" id="modal-approvers"> <button type="button" class="button210" id="modalcloseavail">Close</button> </div> </div> Obviously, form.approvers is going to give me all of the eligible approvers in my form....However I'm just trying to pass the selected approvers... This line of code is working flawlessly.... var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); It is getting the … -
A function working in a custom file but not in a "custom migration" on Django
I am beginner in Django and just started learning migrations. In a DB table, I am trying to remove a row that has a specific field value. When I create a custom file which uses Django settings, the function properly deletes the row. But when I use the snippet in another function in a custom migration file, the deletion doesn't take place. It is possible that I am missing something elementary as a beginner. So I am trying to delete all orders the status of which is cancelled. The function that works in a separate file is: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_skeleton.settings") django.setup() from main_app.models import Order def delete_test_fnc(): all_orders = Order.objects.all() for i in range(len(all_orders) - 1, -1, -1): order = all_orders[i] if order.status == "Cancelled": order.delete() delete_test_fnc() The custom migration where delete doesnt work (other two modifications work without issues) is: from datetime import timedelta from django.db import migrations CURRENT_ORDERS = [] def modify_delivery_warranty(apps, schema_editor): global CURRENT_ORDERS orders = apps.get_model("main_app", "Order") all_orders = orders.objects.all() CURRENT_ORDERS = all_orders for i in range(len(all_orders) - 1, -1, -1): order = all_orders[i] if order.status == "Cancelled": order.delete() elif order.status == "Pending": order.delivery = order.order_date + timedelta(days=3) elif order.status == "Completed": order.warranty = "24 months" order.save() … -
anyone face this issue in django?
enter image description here when i created a employee form and view the form it show like as image. <tr> <td>{{ form.employee_name.label }}</td> <td>{{ record.employee_name }}</td> </tr> <tr> <td>{{ form.dob.label }}</td> <td>{{ record.dob }}</td> </tr> <tr> <td>{{ form.age.label }}</td> <td>{{ form.age }}</td> </tr> only age field show like this, i review all my code , it didnt find and issue, if face same issue please help me -
How to clear validation error in django when the value is in timezone and it must be an decimal value?
I am a beginner in django and in fact,now only i started my learning process about django Now i faced an error in my program I created an app and assigned some textfields in it After that i do some modulations and at a particular time,it asks for an argument to be given in my function to run properly and it shows some examples of how the argument be like And i mistakenly give the timezone.now() for a decimalvalue function Now it shows error like "current date time"value must be a decimal number and i am frustrated upon this error So can someone help me to clear this so that i can continue my journey seemlessly I tried to run a program app called products and i give a decimalvalue() in it with a missing argument and it shows an argument must ve given and asks Would you gonna give now? With for an example "timezone.now" And i give the same example as my argument and i get an error which is "current date time" value must be a decimal number And i want to clear the timezone.now function and wanna put some value or something to run the programthis … -
How to hide password field from request.user in django?
i am learning django currently and i have a question about request.user. I have made an custom user model and i use django's built in authentication. When i use login function, everything works right. When i print request.user it returns the current user. When i print request.user.password it returns the user's hashed password. I know that it is not safe to expose user's password in any form. So my question is how can i exclude password field form request.user I have tried to write a serializer but with no success. User's model from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser, BaseUserManager from post.models import Post class UserManager(BaseUserManager): def create_user(self, email, username, fullName, password): if not email: raise ValueError("User must provide Email") if not username: raise ValueError("User must provide username") if not fullName: raise ValueError("User must provide full name") user = self.model( email=self.normalize_email(email), fullName=fullName, username=username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, full_name, password=None): """Create user and give Superuser privilages""" user = self.create_user( email=email, full_name=full_name, username=username, password=password ) user.is_active = True user.is_staff = True user.is_superuser = True print("Superuser privilages activated.") user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField("Email", unique=True) username = models.TextField("Username", max_length=100, unique=True) fullName … -
Running DRF endpoints in a venv with gunicorn
I have some APIs implemented with DRF and I want those to run in a venv. I am using gunicorn. I run gunicorn like this: /path_to_venv/bin/gunicorn But in the API code I log os.getenv('VIRTUAL_ENV') and it's None. Is that valid evidence that the code is not running in the venv? If so, how can I force it to run in the venv? If not, how can I validate that it is running in the venv? -
Extract Musical Notes from Audio to array with FFT
I'm trying to create a project in which I upload an audio file (not necessarily wav) and use FFT endpoint to return an array with the names of the sounds. Currently, I have such code, but even though I upload a file with only the sound A, it receives the value E-10, and when uploading, for example, title, I receive only one sound. Would anyone be able to help me? import os from django.shortcuts import render from django.http import JsonResponse from pydub import AudioSegment import numpy as np from noteQuiz import settings #Names of the notes NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] def freq_to_number(f): return 69 + 12*np.log2(f/440.0) def number_to_freq(n): return 440 * 2.0**((n-69)/12.0) def note_name(n): return NOTE_NAMES[n % 12] + str(int(n/12 - 1)) def find_top_notes(fft, xf): if np.max(fft.real) < 0.001: return [] lst = [x for x in enumerate(fft.real)] lst = sorted(lst, key=lambda x: x[1], reverse=True) idx = 0 found = [] found_note = set() while (idx < len(lst)) and (len(found) < 1): f = xf[lst[idx][0]] n = freq_to_number(f) n0 = int(round(n)) name = note_name(n0) if name not in found_note: found_note.add(name) s = [note_name(n0)] found.append(s) idx += 1 return found def … -
Django broken pipe error when handling large file
A server developed using the Django framework is hosted in a local environment, and a broken pipe error occurs in the process of processing large files. The current problem is the code below, which is to respond by changing the DICOM file to the png extension through a separate view to deal with the DICOM file. There is no problem in normal cases, but a broken pipe error occurs when processing about 15MB of files. # javascript code for request file data in html template function loadImages(images, fileType, index) { event.preventDefault(); if (index < images.length) { var image = images[index]; var fileName = image.image_url.split('/').pop(); var imageData = { fileName: fileName, }; imageInfoArray.push(imageData); var img = new Image(); img.onload = function() { var filePreviewHTML = ` <li class="add-image-${index}"> <a href="javascript:void(0)" class="img-wrap" data-id="${index}"> <img src="${(fileName.endsWith('.DCM')) ? '/dicom/' + fileName : image.image_url}" alt="ask-file-img"/> <button class="remove-file" onclick="disableImage('${image.image_url}')"><i class="material-icons">close</i></button> </a> <p class="file-name">${fileName}</p> </li> `; var filePreview = $('.file-preview[data-file="' + fileType + '"]'); filePreview.append(filePreviewHTML); loadImages(images, fileType, index + 1); } img.src = (fileName.endsWith('.DCM')) ? '/dicom/' + fileName : image.image_url; } // view code for handling DICOM file def show_dicom(request, file_path): file_path = os.path.join(settings.MEDIA_ROOT, "xray_images", file_path) dicom = pydicom.dcmread(file_path) image_array = apply_voi_lut(dicom.pixel_array, dicom) image_array_2d = image_array[0] if … -
Flutter Web: Assets Not Loading Correctly from main.dart.js Using Current Relative URL Instead of Base HREF
I'm currently working on hosting a Flutter web application using a Django web server on an Ubuntu 20.2 environment. The Flutter version I'm using is 3.13.5, channel stable, and my project structure has the Flutter web project located in the static folder. I've been facing an issue where the Flutter web application cannot locate the FontManifest.json file. It seems like this file is being sought using the current URL (relative) instead of the base URL defined in the index.html file. Assets loaded from index.html work correctly with the base href directed to static directory, but those loaded from main.dart.js and are using the current URL. Has anyone encountered a similar issue or has insights on how to ensure that all assets, including FontManifest.json, loaded from main.dart.js use the base URL as intended? I am almost inclined to reference the missing visual assets in main.dart through the Network module but I think Flutter should have a configuration option to determine the static-uri-location where the app will be hosted with all it's static files instead of just having to rely on the relative-uri for static files. 1.I tried fetching those 2 files (AssetManifest.bin + FontManifest.json) through the main.dart.js but that does not … -
Django not saving data with post
I have this view: class TaskApiView(APIView): def post(self, request): serializer = TaskSerializer(data=request.data) print(request.data) if serializer.is_valid(): print("valid") serializer.save() return Response(status=status.HTTP_201_CREATED) else: print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) request body: { "content": "asd" } log: {'content': 'asd'} valid [21/Oct/2023 11:33:19] "POST /api/task/create HTTP/1.1" 201 0 But when I try to get all tasks with this view class TaskListAPIView(generics.ListAPIView): queryset = Task.objects.all() serializer_class = TaskSerializer I get just the id: [ { "id": 25 } ] Serializer: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = "__all__" Model id: models.UUIDField(unique=True, auto_created=True) content: models.CharField(default="") creationDate: models.DateField(auto_now_add=True) author: models.ForeignKey(User, on_delete=models.CASCADE) status: models.CharField( choices=StatusEnum, max_length=5, default=StatusEnum.TODO, ) def __str__(self): return self.id + self.content I want to create a task with content -
how to pass domain name to the container in Container Instances, OCI?
I am running Django application image in container that requires "CSRF_TRUSTED_ORIGINS" to be passed as env variable, but it looks like container instances generate the domain after the deployment; or how can I set the env variable of container DJANGO_CSRF_TRUSTED_ORIGINS="container instance domain" before running the container. -
Getting a 404 error when sending a POST request with APIClient in Django test case
I'm writing a test case for a Django REST Framework API using the APIClient from the rest_framework.test module. I'm trying to send a POST request to the wordOftheDay/ endpoint with the provided data, but I keep getting a 404 error. The server is running and accessible at http://127.0.0.1:8000, and the endpoint is correctly defined in the server's code. I'm not sure what is causing the 404 error in the test case. def test_valid_post_request(self): client = APIClient() print(client) response = client.post('wordOftheDay/', self.valid_data, format='json') print('response',response) self.assertEqual(response.status_code, 200) print('response.status_code',response.status_code) # Check if the model is created with the expected data self.assertTrue(WordModel.objects.filter(device_id=self.valid_data['device_id']).exists()) This is the error - Traceback (most recent call last): File "/home/k/Desktop/project/wordOfTheDay/tests/test_wordOfTheDay.py", line 88, in test_valid_post_request self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 -
How to Save The Form We Created
Form.save not working Hello guys, I created a form myself without using ModelForm self fields to design it on my own by using css and html but at the end form.save not using ı have no idea what to do /////////////////////////////////////////////////////////////////////////////////////////////// This is my view, class ContactView(View): def get(self,request,*args,**kwargs): return render(request,'contact.html') def post(self,request,*args,**kwargs): form = Form(request.POST) if form.is_valid(): newUser = form.save() return redirect('homepage') return render(request,'contact.html',{'form':form}) This is my html, <form method="post"> {% csrf_token %} <div> <h2 style="margin-bottom: 40px; width: 100%; text-align: center;">Get İn Touch</h2> <div><input type="text" placeholder="Name" name="Name"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><input type="text" placeholder="E-mail" name="E-mail"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><input type="text" placeholder="Subject" name="Subject"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><textarea name="" id="" cols="66" rows="10" style="display: block;" placeholder="Message" name="Message"></textarea> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div class="button"> <button type="submit" value="Submit">Send an email</button> </div> </div> </form> this is my form, class Form(forms.ModelForm): Name = forms.CharField(max_length=50) Email = forms.CharField(max_length=100) Subject = forms.CharField(max_length=50) Message = forms.CharField(widget=forms.Textarea) class Meta: model … -
Reverse for 'posts-details-page' with arguments '('',)' not found. 1 pattern(s) tried: ['all_posts/(?P<slug>[-a-zA-Z0-9_]+)$']
I have build the basic Django project but getting error while trying to retrive all the post from the project. you can download the code from github to create the issue, Please guide me how to resolve this issue if anyone can help. https://github.com/techiekamran/BlogProject.git and branch name is starting-blog-project urls.py from django.urls import path from blogapp import views urlpatterns = [ path("",views.starting_page,name='starting-page'), path("posts",views.posts,name="posts-page"), path("all_posts/<slug:slug>",views.post_details,name='posts-details-page'), #posts/my-first-post ] views.py from datetime import date from django.shortcuts import render def get_date(all_posts): return all_posts['date'] def starting_page(request): sorted_post = sorted(all_posts,key=get_date) latest_post = sorted_post[-3:] return render(request,'blogapp/index.html',{'posts':latest_post}) def posts(request): return render(request,'blogapp/all-posts.html',{'all_posts':all_posts}) def post_details(request,slug): identified_post=next(post for post in all_posts if post['slug']==slug) return render(request,'blogapp/post-details.html',{'post':identified_post}) index.html {% extends "_base.html" %} {% load static %} {% block title %} Home {% endblock %} {% block css_files %} <link rel="stylesheet" href="{% static 'blogapp/post.css' %}"/> <link rel="stylesheet" href="{% static 'blogapp/index.css' %}"/> {% endblock %} {% block content %} <section id="welcome"> <header> <img src="{% static 'blogapp/images/max.png' %}" alt="Max= The author of this Blog"/> <h2>Demo blog des</h2> </header> <p>Hi, this is the our first blog</p> </section> <section id="latest-posts"> <h2>My latest thoughts</h2> <ul> {% for post in posts %} {% include 'blogapp/includes/post.html' %} {% endfor %} </ul> </section> <section id="about"> <h2>What I do </h2> <p>I love programming</p> … -
Efficient way of rank update based on points
User_team=User_team.objects.filter().values(), User_team=[{team_id:1, points:50},{team_id:2, points:30},{team_id:3, points:70}] I already migrate New model and key is (rank,point) stored rank and points in this model. User_team_event=User_team_event.objects.filter().values(). I'm expecting answer is without using loops: User_team_event=[{team_id:3,rank:1, points:70},{team_id:1,rank:2, points:50},{team_id:2, points:30}] -
What is the Sever IP Address
Hi sir i have hosted my python application on pythonanywhere and i am using external api which required ip whitelisting for payment processing , I would like to know the sever ip and is it static or dynamic I am unable to locate the sever ip from my dashboard. -
This field is required error in the "Form" class
I have a problem in my form. When I print the error it says "The field is required". can anyone tell me what I am missing. here is my code forms.py: from django import forms class LoginAuth(forms.Form): Email= forms.EmailField() Password= forms.CharField(max_length=300) views.py: from django.shortcuts import render from .forms import LoginAuth def login(request): if request.method=="POST": form = LoginAuth(request.POST) if form.is_valid(): Email= form.cleaned_data['email'] Password= form.cleaned_data['pass'] request.session['user']= Email request.session.set_expiry(2) print("The form is validated") else: print(form.errors) return render(request, "login.html") login.html: {% extends 'base.html' %} {% block content %} <form method="post"> {% csrf_token %} <input type="email" name="email" placeholder="Enter Email"> <br> <input type="password" name="pass" placeholder="Enter Password"> <br> <br> <input type="submit"> </form> {% endblock %} -
raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
while creating a custom user through the postman api on django im facing this repetedly. please help me to resolve this models.py ROLES = ( (1, 'admin'), (2, 'customer'), (3, 'seller'), ) STATE_CHOICES = ( ('Odisha', 'Odisha'), ('Karnataka', 'Karnataka') ) class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError('The email is not given') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.is_active = True user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if not extra_fields.get('is_staff'): raise ValueError('Superuser must have is_staff = True') if not extra_fields.get('is_superuser'): raise ValueError('Superuser must have is_superuser = True') return self.create_user(email, password, **extra_fields) class Roles(models.Model): role = models.SmallIntegerField(choices=ROLES) class Custom_User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=100) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) role = models.ForeignKey(Roles, on_delete=models.CASCADE) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def add_to_group(self): role_instance = self.role group_name = None if role_instance.role == 4: group_name = 'admin' elif role_instance.role == 5: group_name = 'customer' elif role_instance.role == 6: group_name = 'seller' if group_name: group, created = Group.objects.get_or_create(name=group_name) self.groups.set([group]) return self USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['role'] objects = UserManager() def __str__(self): return self.email def has_module_perms(self, app_label): return True def … -
no such column: api_task.content during makemigraions
When trying ./manage.py runserver or ./manage.py makemigrations or ./manage.py migrate I am getting: django.db.utils.OperationalError: no such column: api_task.content All solutions say to remove db.sqlite3 remove migrations folder run ./manage.py makemigrations; ./manage.py migrate I did 1 and 2, but when trying to do 3 I get the error above (both commands, along with ./manage.py runserver. I am really confused as to why since, yes, it's obviously missing, but it should get recreated. My aim was to clear the db, and since django recreates the db file, I should be able to just delete and make migrations, but I must be missing smth. Task model: import uuid from django.db import models from django.contrib.auth.models import User class Task(models.Model): id: str = models.UUIDField( unique=True, auto_created=True, primary_key=True, default=uuid.uuid4, editable=False, ) content: str = models.CharField( default="", max_length=255, ) deadline: int = models.IntegerField( default=None, null=True, blank=True, ) creationDate: models.DateField(auto_now_add=True) author: models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) -> str: return str(self.id) + str(self.content) -
Django Objects Filter received a naive datetime while time zone support is active when using min max range
So this question is specifically about querying a timezone aware date range with max min in Django 4.2. Timezone is set as TIME_ZONE = 'UTC' in settings.py and the model in question has two fields: open_to_readers = models.DateTimeField(auto_now=False, verbose_name="Campaign Opens") close_to_readers = models.DateTimeField(auto_now=False, verbose_name="Campaign Closes") The query looks like allcampaigns = Campaigns.objects.filter(open_to_readers__lte=today_min, close_to_readers__gt=today_max) Failed Solution 1 today_min = datetime.combine(timezone.now().date(), datetime.today().time().min) today_max = datetime.combine(timezone.now().date(), datetime.today().time().max) print("Today Min", today_min, " & Today Max", today_max) returns the following which would be a suitable date range except it also gives the error below for both min and max. Today Min 2023-10-21 00:00:00 & Today Max 2023-10-21 23:59:59.999999 DateTimeField ... received a naive datetime (9999-12-31 23:59:59.999999) while time zone support is active. Partial Working Solution today_min = timezone.now() allcampaigns = Campaigns.objects.filter(open_to_readers__lte=today_min, close_to_readers__gt=today_min) Returns results without error but the time given is the current time and not the minimum or maximum for the day. Failed Solution 2 from here: now = datetime.now(timezone.get_default_timezone()) today_min = now.min today_max = now.max print("Today Min", today_min, " & Today Max", today_max) Returns Today Min 0001-01-01 00:00:00 & Today Max 9999-12-31 23:59:59.999999 and the aforementioned timezone error. How can I create two timezone aware datetime for the minumum and maximum parts of … -
Django memory Leakage/ less worker
I am working on a project where I have to integrate ML and django together. when running the app there is some lag in compiling and after several minutes i am getting this: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. what is it? how can i solve this? The project should have fetched the data from datasets and then compare the user input and show the result. -
Count of records created in each hour interval starting from midnight to present time
I need to retrieve count of records created in each hour duration from midnight to present time. To do so the model contain a created_at timestamp field which will record the created time. The model definition is given bellow. class Token(models.Model): customer_name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) remarks = models.TextField(null=True,blank=True) modified_at = models.DateTimeField(auto_now =True) The result am looking for like the following in SQL output Intervel | count| -----------------| 01:00 AM | 0 | # 00:00 to 01:00 AM 02:00 AM | 0 | ....... 10:00 AM | 20 | 11:00 AM | 5 | ........ 03:00 PM | 5 | ------------------ I need to get model query that can do the above operation at the database end without loading all the records created in the day since from midnight to now then getting the count by running a forloop in the application. Kindly Help me in this..