Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why i get [Errno 1131 No route to host in django
In a button click, I need to send an email to the client but I actually get this error. OSError at /insurance-company/requests/63256/accept-policy/ [Errno 1131 No route to host Request Method: POST Request URL: ...... Django Version: 3.2.16 Exception Type: OSError exceorion vanes erno 113 No rouce co nose Exception Location: /us/local/lib/python3.8/socket.py, line 796, in create_connection evthon Executable: /usrocaloin/ovthon ryton version: 3.0.1 Python Path: app' 'Jus/local/bin', rusr/local/aao/pychones.21ps /us~/ocal/110/pychons.s; usr/local/11o/python3.8/lib-dynload" Server time: Thu, 11 May 2023 09:07:27 +0000 Note: I only get this in the prod env, but not in my local enviroinment -
"TypeError: NetworkError when attempting to fetch resource", When trying to fetch JSON data on React native from Djang rest framework
I have some JSON data in a Django app, I deployed the app on AWS, when I try to access it on my browser it works fine, but when I try to fetch on React native, I get: "TypeError: NetworkError when attempting to fetch resource". That's my code on expo snack: import React, { useState, useEffect } from 'react'; import { Text, View } from 'react-native'; const App = () => { const [movies, setMovies] = useState([]); useEffect(() => { const fetchMovies = async () => { try { const response = await fetch( 'http://53.27.198.111:8000/api/' //that's not my real IP btw ); const data = await response.json(); setMovies(data.results); } catch (error) { alert(error); } }; fetchMovies(); }, []); return ( <View> <Text>Loading...</Text> </View> ); }; export default App; I tried django-cors-headers when the Django app was on localhost and it worked fine, but when I deployed it on AWS it's not working anymore. -
How to send request million times using httpx
everyone I am building a website that gets user account information from several websites. I have to build training data and I need a lot of them. So if I input a name "e.g. John Smith" it generates a million of names from it and gets user account information from several websites. I used python httpx to send request and it takes about 5seconds for each user. Is it possible for million of names? Or are there any ways to send request with million of names at once? Thanks for your help. I sent requests using httpx and it costs about 5 seconds for each username. And it is estimates more than a year for millions of names. -
How Can I Write and Run a Django User Registration Unit Test Case
I am working on a Django Project that contain two apps; account and realestate and I have a user registration form for registration. This Registration Form is working correctly on my local machine but I want to write and run a Django Unit test for it to be sure everything is working internally well. Below is my Registration Form code: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Define the user_type choices USER_TYPE_CHOICES = ( ('landlord', 'Landlord'), ('agent', 'Agent'), ('prospect', 'Prospect'), ) # Create the registration form class RegistrationForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control left-label'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control left-label'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control left-label'})) user_type = forms.ChoiceField(choices=USER_TYPE_CHOICES, widget=forms.Select(attrs={'class': 'form-control left-label'})) class Meta: model = User fields = ['username', 'password1', 'password2', 'user_type'] Here is my User Registration View code: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): # Create a new user object user = form.save() # Get the user_type value from the form user_type = form.cleaned_data['user_type'] # Create a new object based on the user_type if user_type == 'landlord': Landlord.objects.create(user=user) elif user_type == 'agent': Agent.objects.create(user=user) elif user_type == 'prospect': Prospect.objects.create(user=user) # Log the user in and redirect to the homepage login(request, user) … -
Use Backblaze as Django Default Storage
I want to use Backblaze to serve media files only in Django. I have used django-storages for that purpose, and as per it's documentation it support Backblaze. I used the below configuration in settings.py - INSTALLED_APPS = [ ............ 'storages', 'boto', ] STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", }, "staticfiles": { "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", }, } AWS_ACCESS_KEY_ID = "<my_backblaze_application_keyID>" AWS_SECRET_ACCESS_KEY = "<my_backblaze_applicationKey>" AWS_STORAGE_BUCKET_NAME = "<my_public_bucket_name>" AWS_S3_REGION_NAME = "<region_set_by_backblaze>" AWS_S3_ENDPOINT = f"s3.{AWS_S3_REGION_NAME}.backblazeb2.com" AWS_S3_ENDPOINT_URL = f"https://{AWS_S3_ENDPOINT}" AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.{AWS_S3_ENDPOINT}' MEDIA_URL = '/media/' But the files are not uploading in the Backblaze. How to implement that properly? -
Getting multiple Items using getlist in Django not Working: Return []
I have an issue where the value of multiple item didn't reflect at all to my views.py request.POST.getlist('listitems[]') Returns when print [] selected_items looks like in my ajax when console ajax $.ajax({ type: "POST", url: "{% url 'sales-item' %}", data:{ listitems : selected_items, item_size: selected_items.length} }).done(function(data){ ......... views.py I want to insert it multiple to database but it seems before that happen when I tried to print the item_list it doesn't work it returs [] Did I miss something? item_size = request.POST.get('item_size') item_list = request.POST.getlist('listitems[]') print(item_list) //doesnt work for i in item_size: out_items = request.POST.getlist('listitems['+i+']') print(out_items) additems = table1(quantity = out_items[quantity]) addsales.save() -
Is it possible to save a file to a folder on your local machine when running Django in a Docker Container?
I have created an app in Django (which runs in a Docker Container) that takes several inputs from a form. Based on the inputs a python scripts runs that creates a PDF file in a certain folder. It works fine when I save the PDF in a folder within the app ('static/createdpdf'). However, I would like to be able to save to a directory on my local machine. When I try this I get an Exception File Not Found. I tried to add a function that saves it in my app first and then moves it to my local machine folder, but that doesn't work either. Any suggestions? import shutil import os def movefiles(): filename = 'Testinvoice.PDF' src_path = 'static/images/' dst_path = '/Users/jeandelisseen/Desktop/Testfolder/') filestring_src = os.path.join(src_path, filename) filestring_dst = os.path.join(dst_path, filename) shutil.move(filestring_src, filestring_dst) My Docker File and Docker-Compose files are still pretty basic: # Pull base image FROM python:3.10 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ version: '3.10' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code … -
How to acess Foreign key on django template languages from queryset values
Here is my model class MainCategory(models.Model): name = models.CharField(max_length=100) def __str__(self) : return self.name class Category(models.Model): main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, related_name="maincategory") name = models.CharField(max_length=100) def __str__(self) : return self.name + "--" + self.main_category.name class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_name") name = models.CharField(max_length=100) def __str__(self) : return self.name View def Home(request): sliders = Slider.objects.all() banners = BannerArea.objects.all() main_category = MainCategory.objects.all() context = { 'sliders' : sliders, 'banners' : banners, 'main_category' : main_category } return render(request, 'main/home.html', context) I want to display Main Category and Sub category and category. Main Category is displayed but sub category and category are not displayed. Can you help me to fix this problem Header.html files <div class="cat__menu"> <nav id="mobile-menu" style="display: block;"> <ul> {% for i in main_category %} <li> <a href="shop.html"> {{ i.name }} <i class="far fa-angle-down"></i></a> <ul class="mega-menu"> {% for cat in i.category_set.all %} <li><a href="shop.html">{{cat.name}}</a> <ul class="mega-item"> {% for sub_cat in cat.subcategory_set.all %} <li><a href="product-details.html">{{sub_cat.name}}</a></li> {% endfor %} </ul> </li> {% endfor %} </ul> </li> {% endfor %} </ul> </nav> </div> I want to display Main Category and Sub category and category. Main Category is displayed but sub category and category are not displayed. Can you help me to fix this problem -
Flow Based Visual Programming in Django
I am working with a Django Application for E-Commerce, where I have to build a visaul programming (Flow Based) feature. I came across two JS libraries RETE.JS and NODE-RED. Node-RED is pretty powerfull tool, but it seem pretty difficult to integrate with Django application, as it is a node app. Also, I tried running it on port 1880 and loading it as <iframe>, which worked. But, still creating a lot of e-commerce custom nodes in NODEJS is big deal for me. (I am more into Python, Jquery, Normal Js but not in NODE.JS) For retejs, there is no sidebar list of flow controls, meta fields for controls, like Node-Red already have. Can you suggest some Open-Source JS based library which you help me develope some feature like in image attached. (Attached image is screenshot of feature from some company's platform) -
i want to display 'yyy' in the index.html.but when i run the server ,the page displayed normally but 'yyy' was not display . may i know why ?thanks
i want to display 'yyy' in the index.html.but when i run the server ,the page displayed normally but 'yyy' was not display view.py def index(request): a1='yyy' return render(request, "index.html", a1) index.html i want to display 'yyy' in the index.html.but when i run the server ,the page displayed normally but 'yyy' was not display . may i know why ?thanksenter image description here django python python manage.py runserver,successly .and no mistakes appear. i want to know why ? -
How to create forms from next js , I am getting 400 Bad Request
**I am using Django as backend and next js as frontend and while creating rest api and sending value its working its been created but when i am using next js then i got status 400 Bad Request Can anyone please help me ** My code is listed bellow **This is my next js file ** import { motion, AnimatePresence } from "framer-motion"; import React ,{useEffect , useState ,useRef } from 'react' import CancelIcon from '@mui/icons-material/Cancel'; import {Box,Grid, TextField, Select, MenuItem, Button, FormControl, InputLabel } from '@mui/material'; import { makeStyles , styled , useTheme } from '@mui/styles'; import style from '../src/styles/globals.module.css'; import Form from "react-jsonschema-form"; import axios from 'axios'; const useStyles = makeStyles((theme) => ({ formControl: { margin: theme.spacing(1), minWidth: 120, }, selectEmpty: { marginTop: theme.spacing(2), }, })); function Styledfield() { const [girl, setgirl] = useState([]); const [boy, setboy] = useState([]); const [data, setData] = useState({ ids: 0, value: 0.0, Name: '', SurName: '', Gender: '', Diffrent_Family: '', Born_Place: '', Date_Of_Birth: '', Status: '', Date_Of_Death: '', Marrital_Status: '', Wife: '', parent: '', Mother: '', image: null }); useEffect(() => { Promise.all([ axios.get('http://127.0.0.1:8000/media/boys/'), axios.get('http://127.0.0.1:8000/media/girls/') ]) .then(([boysResponse, girlsResponse]) => { setboy(boysResponse.data); setgirl(girlsResponse.data); // console.log("Boys: ", boysResponse.data); // console.log("Girls: ", girlsResponse.data); }) .catch(error … -
Running Multiple Gunicorn Instances for Low-Traffic Websites
I've been exploring the use of Gunicorn and Nginx to serve Django websites, and it's generally recommended for its performance benefits. However, I have a question regarding running multiple websites on the same server with Gunicorn. If I want to run multiple websites, it seems that I need to run separate instances of Gunicorn for each site. My concern is whether this approach will unnecessarily consume CPU and RAM resources, especially if the websites have low traffic. In the past, I've used a LAMP stack to run multiple websites without requiring dedicated processes for each site. This makes me wonder if the modern approach with Gunicorn and Nginx is better in terms of resource usage and efficiency. Could anyone shed some light on this? Am I missing something in understanding the benefits of running multiple Gunicorn instances for multiple websites, even if they have low traffic? I appreciate any insights or experiences you can share. Thanks in advance! -
Django: the annotation field conflicts with a field on the model
I have the below code using Django's QuerySet and annotate, in an attempt toleft join 2 tables and replace DocumentModel's column description with the result from another table PackageModel based on the package_id qs = DocumentModel.objects.filter(**some_filters).filter(s_query) packages = PackageModel.objects.filter( document_id=OuterRef("document__uuid") ).values("description")[:1] qs = qs.annotate( description=Coalesce(Subquery(packages), F("description")), ) However, I hit with the following error which is also correct. Both tables have the column description. ValueError: The annotation 'description' conflicts with a field on the model. I have try a few possible solutions, but I still can't get it to work. Option 1. Change from description to package_description in qs.annotate(), but that's not what I wanted. I actually want to replace the content from PackageModel. Option 2. Introduce a foreign-key, but the limitation prevents me from running other migration on this Django project. It also has existing content already in the DocumentModel description that we need to handle the deprecation separately, not in this change. Option 3. Following a suggestion from another Stackoverflow post, however, the result QuerySet would return as a dict which is not what we want. We want the return type stays the same as DocumentModel. fields = [field.name for field in DocumentModel._meta.get_fields()] fields.remove("description") qs = qs.values(*fields) Does … -
when the user logged in. its not redirecting to comments page .when i added ID..to comments in urls.py.. not redirecting.How to add id for comments?
NoReverseMatch at /login/ reverse for 'comments' with no arguments not found. 2 pattern(s) tried: ['comments/(?p[0-9]+)\z', '\ comments/(?p[0-9]+)/\z'] return redirect ('comments') //this line is highliting def login_user(request,): if request.user.is_authenticated: return redirect('/') if request.method=='POST': email=request.POST.get('email') password = request.POST.get('pwd') user = authenticate(request,email=email,password=password) if user is not None: login(request,user) return redirect ('comments')//this line is showing error i think// else: return HttpResponse('details wrong') return render(request,'events/login.html') @login_required(login_url="/login") def comments(request,id): if request.method=='POST': rating=request.POST['rating'] review_title=request.POST['review_title'] review=request.POST['review'] good=request.POST['good'] bad=request.POST['bad'] product=Product.objects.get(pk=id) user=request.user mydata=Post(men=user,product=product, rating=rating,review_title=review_title,review=review,positive_points=good,Negative_points=bad) mydata.save() return render(request,'events/comments.html') urls.py path(' comments/int:id/',views.comments,name="comments"), path('login/',views.login_user,name='login' ), how to add id to comments page like.... return redirect ('comments')//this line -
autodiscover_tasks did not get the task under the django app
When I use the following code to get celery tasks in the view file, I only get the tasks related to celery itself, but not the tasks under the django app. from myproj.celery import app print(app.tasks) '''OUTPUT: {'celery.group': <@task: celery.group of myproj at 0x7fa640101940>, 'celery.map': <@task: celery.map of myproj at 0x7fa640101940>, 'celery.chain': <@task: celery.chain of myproj at 0x7fa640101940>, 'celery.backend_cleanup': <@task: celery.backend_cleanup of myproj at 0x7fa640101940>, 'celery.starmap': <@task: celery.starmap of myproj at 0x7fa640101940>, 'celery.chord': <@task: celery.chord of myproj at 0x7fa640101940>, 'celery.accumulate': <@task: celery.accumulate of myproj at 0x7fa640101940>, 'celery.chunks': <@task: celery.chunks of myproj at 0x7fa640101940>, 'celery.chord_unlock': <@task: celery.chord_unlock of myproj at 0x7fa640101940>}''' The task of the current app will only be obtained when I use the following method. from myapp.tasks import app print(app.tasks) Here is the celery file configuration # celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings') app = Celery('myproj') app.conf.update({ 'broker_url': 'redis://localhost:8000/11', 'result_backend': 'django-db', 'accept_content': ['json'], 'task_serializer': 'json', 'result_serializer': 'json', 'worker_force_execv': True, 'worker_concurrency': 10, 'task_time_limit': 60 * 60, 'worker_max_tasks_per_child': 200, 'beat_tz_aware': False, 'result_extended': True, }) app.conf.enable_utc = False app.autodiscover_tasks() This is the task in tasks.py under django app from myproj.celery import app @app.task def add(): x=1 y=y I'm confused, shouldn't autodiscover_tasks automatically discover all … -
What is "can_delete_extra" for in Django Admin?
I have Person model and Email model which has the foreign key of Person model as shown below: # "models.py" class Person(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Email(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) email = models.EmailField() def __str__(self): return self.email Then, I set can_delete_extra = True to Email inline as shown below: # "admin.py" class EmailInline(admin.TabularInline): model = Email can_delete_extra = True # Here @admin.register(Person) class PersonAdmin(admin.ModelAdmin): inlines = (EmailInline,) Or, I set can_delete_extra = False to Email inline as shown below: # "admin.py" class EmailInline(admin.TabularInline): model = Email can_delete_extra = False # Here @admin.register(Person) class PersonAdmin(admin.ModelAdmin): inlines = (EmailInline,) But, nothing happens to DELETE? check boxes on change page as shown below: I know if setting can_delete = False to Email inline as shown below: # "admin.py" class EmailInline(admin.TabularInline): model = Email can_delete = False # Here @admin.register(Person) class PersonAdmin(admin.ModelAdmin): inlines = (EmailInline,) Then, I can hide DELETE? check boxes on change page as shown below: So, what is can_delete_extra for in Django? -
Django in Chart.JS data not plotting properly
I am building a line chart and the data is not plotting against the correct dates. The Chart.js configuration is displayed below: $(document).ready(function(){ const ctx = document.getElementById('myChart').getContext('2d'); const labels = [{% for date in dates %}'{{ date|date }}',{% endfor %}] const myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{% for trial in trial_list %} { label: '{{trial.behavior_name}}', data: '{{trial.frequency_input}}', backgroundColor: 'transparent', borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], tension: 0.4 }, {% endfor %} ] } }); }); Here is the view function i am using: def dashboard(request): # filter list of client sessions by selected client client_sessions = Client_Session.objects.filter(therapist=request.user) client = DashboardClientFilter(request.GET, queryset=client_sessions) client_sessions = client.qs #Create list of Trials across Client Sessions for the filtered client client_pks = client.qs.values_list('client_id',flat=True) trial_list = Trial.objects.filter(client_session__client_id__in=list(client_pks)) #trial_list = trial_list.exclude(duration_input__isnull = False) trial_list = trial_list.order_by('client_session__session_date') print(trial_list) dates=[] for i in range(trial_list.count()) : if trial_list[i].client_session.session_date not in dates : dates.append(trial_list[i].client_session.session_date) trial_list_values = trial_list.values('behavior_name__name','frequency_input','duration_input','client_session__session_date') print('printing trial list values') print(trial_list_values) context = {'client_sessions':client_sessions, 'client':client, 'trial_list':trial_list, 'trial_list_values':trial_list_values,'dates':dates} return render(request, 'dashboard.html', context) THe screenshot below illustrates the issue further. All my data points … -
How can I build Docker image via anaconda
I want to build django project use Docker the following libraries are required Django Pillow opencv-python scipy numpy django-mdeditor markdown django-markdownx mysqlclient Instead of running with Pip command, I want to run with anaconda but I still haven't figured out how to run it. please help me, thank you!!! -
Django IntegerChoices with variable label
I have a class that inherits from models.IntegerChoices and defines certain constants I use in my model. I want to make the "labels" of my integer choices a variable in the settings.py: class Status(models.IntegerChoices): ONE = 0, settings.ONE_LABEL TWO = 1, settings.TWO_LABEL When playing around with this I found that whenever I change ONE_LABEL or TWO_LABEL in my settings, Django would like to create a new migration similar to migrations.AlterField( model_name='mymodel', name='status', field=models.IntegerField(choices=[(0, 'New one label'), (1, 'New two label')], default=0), ) My goal is to deploy multiple (very similar) servers where only UI elements (that display the names of status) change according to the values in my settings. I guess it is not wise to allow changes in my settings to trigger any changes in the database, as that would make updating later versions of my project much harder. Is it safe to ignore the possible migration? I thought the way above is the easiest as I have multiple model forms and other components that use the label of my status class. This would allow a single change in my settings to be transferred throughout my project. I can't see why changing the label would require a DB migration … -
Why is django select2 not showing?
put django-select2 on this and this instruction but select doesn't show what's wrong? maybe because I didn't specify the cache? settings.py INSTALLED_APPS = [ ... 'django_select2', ] main urls.py urlpatterns = [ ... path('select2/', include('django_select2.urls')), ] app models.py class Clients(models.Model): name = models.CharField(max_length=150, blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') phone = models.CharField(validators=[phone_regex], max_length=17) def __str__(self): return self.phone app forms.py class PhoneSelect2Widget(s2forms.ModelSelect2Widget): search_fields = ('phone__icontains',) queryset = Clients.objects.all() class RelatedAddForm(forms.ModelForm): phone = forms.ModelChoiceField( widget=PhoneSelect2Widget(attrs={'class': 'select2'}), queryset=Clients.objects.all()) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(RelatedAddForm, self).__init__(*args, **kwargs) class Meta: model = Clients fields = ['phone'] base.html {% load static %} <html lang="en"> <!--begin::Head--> <head> <title>HUB CRM</title> {{ form.media.css }} <script src="{% static 'jquery/jquery-3.6.0.min.js' %}"></script ... ... {{ form.media.js }} </body> <!--end::Body--> </html> -
create a draggable menu in Django and a custom CMS
I am trying to create a draggable menu in a custom CMS and admin panel for a Django project. I wonder if there is any way to get the new sort of blocks and save it in the database. as an explanation, this is the first order: and it is a draggable sort of block using JQuery. for example the second order of the blocks after dragging some of them: It is ok to show the base order of blocks to admins. But how can I get the new sort in views.py after the admin has changed the sort? HTML <div class="col-sm-8 column"> <div class="block"> <div class="block-title"> <h2>Block #1</h2> </div> <p>...</p> </div> <div class="block"> <div class="block-title"> <h2>Block #2</h2> </div> <p>...</p> </div> </div> <!-- Other Blocks --> </div> JQuery var UiDraggable = function() { return { init: function() { $('.draggable-blocks').sortable({ connectWith: '.block', items: '.block', opacity: 0.75, handle: '.block-title', placeholder: 'draggable-placeholder', tolerance: 'pointer', start: function(e, ui){ ui.placeholder.css('height', ui.item.outerHeight()); } }); } }; }(); -
Get total sum using property in django
Hello friends I need help from you! The question is that I am making an application to save the consumption of energy meters, where I receive the daily reading of the meters and using property I calculate the consumption of the reading received from the current day compared to the last day, I also calculate the total consumption of the consumptions diaries. class ConsumoElect(models.Model): pgd = models.ForeignKey(TipoPGD, on_delete=models.CASCADE, related_name='consumoelect') fecha = models.DateField(default=datetime.now) fecha_AM = models.CharField(max_length=20) lec_madrugada = models.IntegerField(default=0) lec_dia = models.IntegerField(default=0) lec_pico = models.IntegerField(default=0) reactivo = models.IntegerField(default=0) dato = models.IntegerField(default=0) total = models.IntegerField(default=0) def __str__(self): return '%s' % (self.pgd) def get_cm(self): c_m = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_madrugada', 'fecha')) if not c_m: return 0 else: if not c_m[0]['lec_madrugada']: return 0 else: return ((c_m[0]['lec_madrugada'] - self.lec_madrugada)) consumo_madrugada= property(get_cm) def get_cd(self): c_d = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_dia')[0:1]) if not c_d: return 0 else: if not c_d[0]['lec_dia']: return 0 else: return ((c_d[0]['lec_dia'] - self.lec_dia)) consumo_dia= property(get_cd) def get_cp(self): c_p = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_pico')[0:1]) if not c_p: return 0 else: if not c_p[0]['lec_pico']: return 0 else: return ((c_p[0]['lec_pico'] - self.lec_pico)) consumo_pico= property(get_cp) def get_total(self): return (self.consumo_dia + self.consumo_madrugada + self.consumo_pico) consumo_total= property(get_total) def save(self, *args, **kwargs): fe=date.strftime(self.fecha, "%Y-%m") self.fecha_AM = fe return super().save(*args, **kwargs) class Meta: unique_together=['pgd', 'fecha'] verbose_name = 'Consumo Electrico' verbose_name_plural … -
Django Filter model by Day of Date
I am at a loss. What I'm doing is very simple and works in dev but not prod. I have a model, EmailLog, which contains a DateTimeField with a default of timezone.now. Model is created in database with the correct timestamp. I would like to display any models that were created today. Model Snippet class EmailLog(models.Model): created_on = models.DateTimeField(default=timezone.now) ... Model shows in database as 2023-05-10 16:31:34.381 for created_on and a raw print(log.created_on) shows 2023-05-10 16:31:34.381741+00:00 I'm attempting to pull logs for today like so logs = list(EmailLog.objects.filter(created_on__day=10, created_on__month=5)) This works perfectly fine in dev, in production I'm given no results but also no errors. I've tried created_on__date=timezone.now().date(), created_on__gte=timezone.now().date(), also tried various forms of the date in string ISO format 2023-05-10, I've tried created_on__range=(start_date,end_date) where start_date is 2023-05-10 00:00:00 and end_date is 2023-05-10 23:59:59 and I get nothing. Both dev and prod database are MySQL, but quite possibly different versions as the production app is in Azure using an Azure MySQL. That is the only difference I can see between app deployments, both are using a virtual env, both configured with some packages, all managed with poetry and identical. I'm at a loss, please point out the bonehead mistake I'm … -
upload image to db using image url (DJANGO)
Im new to django and im trying to upload a specific image from html form to the django database using its url. I found multiple ways to do so, but they all use the "browse" button and makes the user manually choose which image to upload (see image below). Is there a way to automatically look for and upload a specific image thats already in my device using image url? -
Stop the main thread until all task done in a ThreadPoolExecutor - Python DJANGO
I've some rather heavy stored procedures in a view and I wanted to use threads to execute those queries in parallel but I don't know how to stop the main thread until those queries have finished. My code: from concurrent.futures import ThreadPoolExecutor def resultados(request): executor = ThreadPoolExecutor() context = {} executor.submit(resultados_proceso, regiones, territorios, canales, marcas, periodos) executor.submit(resultadosGrafica_proceso,regiones, territorios, canales, marcas, periodos) executor.submit(get_volumen_ejecucion_clientes_iniciativa, 106) executor.submit(get_volumenAP_xmarca, ['M']) return render(request, 'resultados.html', context) def resultados_proceso(context, regiones, territorios, canales, marcas, periodos): context['resultados'] = getResultados(regiones, territorios, canales, marcas, periodos) def resultadosGrafica_proceso(context, regiones, territorios, canales, marcas, periodos): context['grafica'] = getResultadosGrafica(regiones, territorios, canales, marcas, periodos)