Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to covert django created_at/date_joined time to current user time?
I am getting the user object using user = User.objects.all() context = {'user':user} Passing it to context then using in templates {% for i in user %} <h1>{{i.first_name}}<h1> <h1>{{i.date_joined}}</h1> {% endfor %} Right now i am getting server time but i want to get the time as per the current user country time? How it can be possible? -
Django doesn't find Pillow "Cannot use ImageField because Pillow is not installed." Windows 10 Version 22H2 Build19045
I installing Pillow successfully inside of the venv. but I still get the same Error when starting the server. D:\Commerce>python manage.py runserver django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: auctions.listings.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". System check identified 1 issue (0 silenced). I have Python version 3.11.1 installed. Pillow Version Support in an activated venv I checked for: pip --version pip 22.3.1 from D:\Commerce\venv\Lib\site-packages\pip (python 3.11) The Installation Directory of Django and Pillow are the same as you can see below. And both are updated to the newest version. pip show django Name: Django Version: 4.1.5 Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design. Home-page: https://www.djangoproject.com/ Author: Django Software Foundation Author-email: foundation@djangoproject.com License: BSD-3-Clause Location: D:\Commerce\venv\Lib\site-packages Requires: asgiref, sqlparse, tzdata Required-by: pip show Pillow Name: Pillow Version: 9.4.0 Summary: Python Imaging Library (Fork) Home-page: https://python-pillow.org Author: Alex Clark (PIL Fork Author) Author-email: aclark@python-pillow.org License: HPND Location: D:\Commerce\venv\Lib\site-packages Requires: Required-by: I tried pip uninstall Pillow pip install Pillow and pip uninstall Pillow python -m pip install Pillow I updated Python, Django, PIP and Pillow. Python via the … -
Django didn't save data to postgre during test case executing
I have webapp, which has a lot of big calculation logic. To stable it and spend less time to regress tests I decided to create some unit test cases on Django. My purpose - don't create new test DB (I use Postgre SQL, is important) for every testcases running and save DB with all test data after test cases finished. I need to have test data for analysis and search bugs. I created custom TestRunner, which inherited on DiscoverRunner with change some parameters: keepdb = True debug_mode = True verbosity = 2 This thing is work, I reuse one DB for all test-cases. My problem is I don't see test data which created during test cases in my test DB. I had some failed testcases or all OK - nothing change. Interesting facts for me: During test cases I have some queries to DB about new test data and these queries returns right result. During test cases I created new objects and sequences in DB are changed as if test data exists in DB. What I do wrong? -
Failed to read dockerfile
I'm trying to dockerize my djangp app with postgres db and I'm having trouble, when run docker-compose, error is: failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount4260694681/Dockerfile: no such file or directory Project structure in screenshot: Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . docker-compose: version: "3.9" services: gunter: restart: always build: . container_name: gunter ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8080 depends_on: - db db: image: postgres Then: docker-compose run gunter What am I doing wrong? I tried to change directories, but everything seems to be correct, I tried to change the location of the Dockerfile -
Next.JS frontend does not have csrf token which is from Django-Backend
I am super newbie in programming. I am using Django as Backend, Next.JS as Frontend. I have a session login function which works perfect on "runserver"+"localhost:3000" But It is not work on production. I found that there is no cookie on my production mode. which is existing on development mode. below picture is from inspect mode on chrome. like above. there is some data in my development mode. but there is nothing on my production mode. I guess that this makes some errors now. I cannot get data from drf rest api with below code. const instance = axios.create({baseURL: process.env.NODE_ENV === "development" ? "http://127.0.0.1:8000/api/v1/" : "https://mysite/api/v1/",withCredentials: true,xsrfHeaderName: "X-CSRFTOKEN",xsrfCookieName: "csrftoken", }); export const getMe = () => instance .get( `users/me`, { headers: { "X-CSRFToken": Cookie.get("csrftoken") || "", }, } ) .then((response) => response.data); above code gives me "error 500", which should give me User Data. I think that is because of my csrftoken is missing at all in my frontend. My Backend Django settings.py like this. if DEBUG: CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000", "http://localhost:3000", ] else: CSRF_TRUSTED_ORIGINS = [ “myfront.com” ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False Q. How can I fix my getMe function work … -
How to filter nested list of list of objects with JSON field in django
I have a Model named Ad and it has a field named location_details and it's a JSON field. while fetching the list of objects from Model A, I am applying filter for the location_details field http://127.0.0.1:8000/ad-list/?limit=10&offset=0&ordering=-start_date&location_category=bus_station%2Chospital While creating an ad, I compute the nearby places and store it as a JSON field as shown below const NEARBY_PLACES = [ { name: "transit", label: "Transit", sub_categories: [ { name: "bus_station", label: "Bus Stop", values: [{name: 'A'}, {name: 'B'}], }, { name: "airport", label: "Airport", values: [], }, { name: "train_station", label: "Train Station", values: [], }, ], }, { name: "essentials", label: "Essentials", sub_categories: [ { name: "hospital", label: "Hospital", values: [{name: 'te'}], }, { name: "school", label: "Schools", values: [{name: 'B'}], }, { name: "atm", label: "ATMs", values: [], }, { name: "gas_station", label: "Gas Stations", values: [{name: 'C'}], }, { name: "university", label: "Universities", values: [], }, ], }, { name: "utility", label: "Utility", sub_categories: [ { name: "movie_theater", label: "Movie Theater", values: [], }, { name: "shopping_mall", label: "Shopping Mall", values: [], }, ], }, ]; Now, I want to filter the ad list with multiple location_categories with the above JSON object and want to filter if the … -
Django form is saved but result field is empty in database
Django form is saved but "result" field is showing empty in database. Even after populating the filed from admin panel, it is saved but it still shows empty. Models.py class Result(models.Model): class Choises(models.TextChoices): POSITIVE = "POSITIVE", "Positive" NEGATIVE = "NEGATIVE", "Negative" user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, default=None) result = models.CharField(max_length = 100, choices=Choises.choices, blank=False ) resultDoc = models.ImageField(upload_to='testResults', height_field=None, width_field=None,) def __str__(self): return self.user.username Forms.py class resultForm(forms.ModelForm): class Meta: model = Result fields = ['name', 'result', 'resultDoc'] views.py def inputResult(request, pk): user = User.objects.filter(id=pk).first() profile = newProfile.objects.filter(user=user).first() if profile == None: profile = oldProfile.objects.filter(user=user).first() rForm = resultForm(request.POST, request.FILES) if request.method == 'POST': rForm = resultForm(request.POST, request.FILES) if rForm.is_valid(): order = rForm.save(commit=False) order.user_id = pk order.save() return redirect('stored_records') else: rForm = resultForm() context = {'user' : user, 'profile':profile, 'rForm': rForm} return render(request, 'Testing booth End/input-result-customer-info.html', context) input-result-customer-info.html <form action="" method = "POST" enctype= "multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="name" class="form-label">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Uploaded By/Doctor Name"> </div> <div class="mb-3"> <label for="result" class="form-label">Result</label> <select class="form-select" id="result" name="result" class="form-control"> <option value="POSITIVE">Positive</option> <option value="NEGATIVE">Negative</option> </select> </div> <div class="mb-3"> <label>Upload Scan File</label> <div class="upload d-flex justify-content-between"> <div class="file-placeholder">Upload Scan File</div> <input type="file" class="form-control d-none" id="resultDoc" name="resultDoc" > <label for="resultDoc" … -
How do I increment a count field automatically within a many to many intermediate table in django models?
So I have the following three models for creating an icecream (which consists of a flavour and the cone of the icecream): from django.db import models not_less_than_zero=MinValueValidator(0) class Flavour(models.Model): name = models.CharField(max_length=255) price = models.DecimalField( max_digits=5, decimal_places=2, validators=([not_less_than_zero]) ) class Icecream(models.Model): cone = models.ForeignKey( Cone, on_delete=models.PROTECT ) scoops = models.ManyToManyField( Flavour, through='quickstart.IcecreamFlavour' ) quantity = models.IntegerField(default=1, validators=([not_less_than_zero])) class IcecreamFlavour(models.Model): icecream = models.ForeignKey(Icecream, on_delete=models.PROTECT) flavour = models.ForeignKey(Flavour, on_delete=models.PROTECT) count = models.IntegerField(blank=True, default=1, validators=([not_less_than_zero])) I would like for the count field in IcecreamFlavour to be updated automatically whenever a flavour is added to Icecream that already exists for that icecream. example in python shell: >>> from .models import Cone, Flavour, Icecream >>> >>> # defining some flavours in the database >>> strawberry = Flavour.objects.create(name="Strawberry", price=0.75) >>> chocolate = Flavour.objects.create(name="Chocolate", price=0.80) >>> >>> # for the purpose of this example, lets say there is already a predefined icecream in the database >>> my_icecream = Icecream.objects.get(pk=1) >>> my_icecream.scoops.add(chocolate) >>> my_icecream.scoops.add(strawberry) >>> my_icecream.scoops.count() # beware! this is not the count field of IcecreamFlavour model 2 >>> # so far so good >>> my_icecream.scoops.add(strawberry) >>> my_icecream.scoops.count() 2 So after seeing this I presumed that this was because there already exists an entry in the intermediate table … -
ValidationError at /admin/projects/project/add/ ['“self” is not a valid UUID.']
Gettin ValidationError at /admin/projects/project/add/ ['“self” is not a valid UUID.'] My model.py `class Project(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # company=models.CharField(max_length=100) created_by=models.ForeignKey(User, on_delete=models.CASCADE) name=models.CharField(max_length=100)` #`admin.py` from django.contrib import admin from . import models # Register your models here. admin.site.register(models.Project)` -
Django REST committing migration files to production
I have a django REST project and a PostgreSQL database deployed to DigitalOcean. When I develop locally, I have a separate dockerized REST server and a separate PostgreSQL database to test backend features without touching production data. My question arises when I'm adding/modifying model fields that require me to make migrations using python [manage.py](https://manage.py) makemigrations and python [manage.py](https://manage.py) migrate command. Here is my current situation so far: I added a model field isActive to User field I ran migration command on local database which created a new file under migrations: 0011_user_isActive.py I committed & pushed the changes to production WITHOUT the created migration file I ran migration command on production database through digitalocean's console The production server successfully added the isActive field to the database and is working fine, but I still have a 0011_user_isActive.py migration file in my local changes that hasn't been staged/committed/pushed to github repo. My questions are: What happens if I push the local migration file to production? Wouldn't it create a conflict when I run migration command on digitalocean console in the future? What am I supposed to do with local migration files that are generated by local migration commands? I am just scared I'm … -
Does my code have to be written in php to intefrate WordPress
Say for instance i have a web application that uses Django as a framework, is there going to be a problem when integrating WordPress? -
unable to connect django sevice with rabbitmq service using docker
I am trying to connect RabbitMQ with Django application. But when I run the command "docker-compose up" I get this error "pika.exceptions.AMQPConnectionError" can someone explain me the reason for this error and also suggest me its solution. I am sharing the code of docker-compose file and the publisher code where the main error is. docker-compose.yml version: '3.8' services: db: image: postgres:9.6-alpine restart: always environment: # - HOST:localhost - POSTGRES_DB=admin - POSTGRES_USER=postgres - POSTGRES_PASSWORD=admin123 # MYSQL_ROOT_PASSWORD: root volumes: - ./postgres-data:/var/lib/postgresql/data ports: - 5432:5432 rabbitmq: image: rabbitmq:3.8-management-alpine hostname: rabbitmq ports: - 15673:15672 environment: - RABBITMQ_DEFAULT_HOST=localhost - RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_PASS=guest backend: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/app environment: - RABBITMQ_DEFAULT_HOST=rabbitmq - RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_PASS=guest depends_on: - db - rabbitmq produce.py import pika, os, django from .models import Product # amqps://bescccok:rsjlBxeksDvwcp23H0QDJh83qttksbsF@sparrow.rmq.cloudamqp.com/bescccok connection = pika.BlockingConnection( pika.ConnectionParameters('localhost') ) channel = connection.channel() def callback(ch, method, properties, body): import json print('Received in admin') id = json.loads(body) product = Product.objects.get(id=id) product.likes = product.likes + 1 print("Product Liked!!! ") channel.basic_consume(queue='admin', on_message_callback=callback, auto_ack=True) print("Started Consuming") channel.start_consuming() channel.close() I tried to changing the hostname in docker-compose file in rabbitmq service and add the servicein pika connection function, still it didn't work. -
How to send image from django html template to view and use the openCv handdetector
I want to use a webcam in my django application and use it to play rock paper scissors with cv2 hand recognition. Basic webcam html template: <div class="container"> <div class="row"> <div class="col-md-6"> <video id="webcam" width="640" height="480" autoplay></video> </div> <div class="col-md-6"> <button id="play-button" class="btn btn-primary" onclick="play()">Play</button> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Function to start the webcam and display the video feed function startWebcam() { navigator.mediaDevices.getUserMedia({ video: true, audio: false }) .then(function(stream) { var video = document.getElementById('webcam'); video.srcObject = stream; video.play(); }) .catch(function(err) { console.log("An error occurred: " + err); }); } // Function to capture the image from the webcam and send it to the Django view function play() { // Stop the video stream from the webcam var video = document.getElementById('webcam'); var stream = video.srcObject; var tracks = stream.getTracks(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.stop(); } // Create a canvas element to draw the image on var canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; var context = canvas.getContext('2d'); context.drawImage(video, 0, 0, canvas.width, canvas.height); // Convert the image to a data URL var imageData = canvas.toDataURL('image/jpeg'); // Send the image to the Django view using an AJAX request … -
How to direct from post to category page in Django?
I'm working on my Django blog. I have a trouble to redirect from post to category, when you open post you can click to category and when you click on category I want you to redirect you to category and show posts only from that category. This part of my html code for post_detail.html <div class="entry-meta meta-0 font-small mb-30"><a href="{{ category_detail.get_absolute_url }}"><span class="post-cat bg-success color-white">{{ post.category}}</span></a></div> <h1 class="post-title mb-30"> {{ post.post_title }} </h1> This is models.py only class category class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") category_name = models.CharField(max_length=255, verbose_name="Category name") slug = models.SlugField(max_length=200, unique=True) def get_absolute_url(self): return reverse('category_detail', args=[self.slug]) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.category_name in post_detail is defined like this (short view) class Post(models.Model): ... post_title = models.CharField(max_length=200, verbose_name="Title") category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) ... def __str__(self): return self.post_title This is views.py def category_detail(request, pk): category = get_object_or_404(Category, pk=pk) return render(request, 'category_detail.html', {'category': category}) This is urls.py from . import views from django.urls import path urlpatterns = [ path('', views.home, name='home'), path('<slug:slug>/', views.post_detail, name='post_detail'), path('<slug:slug>/', views.category_detail, name='category_detail'), ] Any idea why I'm not redirected to category_detail page? Thanks in advance! -
'WSGIRequest' object has no attribute 'request'
I am trying to use a context processor to get the last 10 messages based on the user's organization. What is weird is that I can call self in get_user, but i can't in get_last_10_messages. Any ideas why I get the WSGIRequest issue in one function and not the other? from message.models import Message from contact.models import Contact def get_last_10_messages(self): print(self.request.user.id) user = Contact.objects.get(user_id=self.request.user.id).select_related('organization') last_10_messages = Message.objects.all() return {'last_messages': last_10_messages} def get_user(self): user = Contact.objects.get(user_id=self.request.user.id).select_related('organization') return {'user': user} -
Exception Value: badly formed hexadecimal UUID string
models.py import uuid from django.db import models class Book(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title def get_absolute_url(self): # new return reverse('book_detail', args=[str(self.id)]) "-----------------------------------------------------------------------" ? I want try for better id in models but i had this erorr... who can help me? -
Django URL installation failed
[enter image description here](https://i.stenter image description hereack.imgur.com/S7Ocu.png)enter image description here I am unable to install the url package. after i did pip install url, installation failed -
Django webpage loading issue
I'm creating a project in Django, my admin section is working properly, and models are working properly but when I'm going to open the server to check the landing page, it shows like this attached below. I've created another page and made that page the main landing page but that showed me the same result. Don't know what to do now. -
Finding it difficult to construct login functionalities. Bad request
view.py class Login(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(raise_exception=True): username = serializer.data.get('username') password = serializer.data.get('password') user = authenticate(password=password, username=username) # This line above and below this comment if user is not None: login(request, user) return Response({"msg": "Login Successful"}, status=status.HTTP_200_OK) else: return Response( { "errors": { "non_field_errors": ["Email or Password is not valid"] } }, status=status.HTTP_404_NOT_FOUND ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)pe here serializer.py class LoginSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] api.js import axios from 'axios' export default axios.create({ baseURL:'http://localhost:8000/', } ) signup const onSubmit = e =>{ e.preventDefault() api .post(`user/login/`, JSON.stringify({username, password}), ) .then(({data}) =>{ console.log(data) }) If if try to login on the browser, it returns AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} How to login from reactjs to django(python) -
Don't cross time in the fishing
I'm developing a site for the sport fishing booking at a fish farm. Almost the same as when booking a hotel stay. Only instead of a room - a fishing pier. I want to write a condition for saving data in the reservation database, where the booked time will not overlap with the previously booked one. Taking into account the selected pier. For example: fisherman John has booked "Pier 1" from 6:00 to 13:00. And fisherman Alex wanted to book the same day the same "Pier 1" from 11:00 to 21:00. But the code (perhaps a validator) will not allow Alex to do this, because from 11:00 to 13:00 "Pier 1" is still the time ordered by the fisherman John. Alex can choose another time or choose another "Pier 2", "Pier 3". I hope you understand me. So, the models.py is next from django.utils.translation import gettext_lazy as _ from django.utils.timezone import now from django.contrib.auth.models import User from django.db import models from django.core.exceptions import ValidationError # blocking the reservation time that has passed def validate_past_time(value): today = now() if value < today: raise ValidationError(_(f'{value} less than the current time {today}')) # booking model class BookingPier(models.Model): pier = models.ForeignKey('Pier', on_delete=models.PROTECT, null=True) PIER_STATUS_CHOICES … -
I would like to save my crop image to my django database called model filed file, help appricated - It been 3 days still stuck in this
I have the following models.py class Imageo(models.Model): file = models.ImageField(upload_to='cropped_images') uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.pk) I would like to savemy file into my Imageo models but it is saving into my database some other folder, please look at the views.py file. def con(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = Image.open(form.cleaned_data['file']) image = image.resize((200, 200), PIL.Image.ANTIALIAS) image = image.convert('RGB') dt = image.save('resize.jpg') # i would like to save resize.jpg into my models name called file return HttpResponse('done') else: form = ImageForm() img = Imageo.objects.latest('id') return render(request, 'NEC/imgCon.html', {'form': form, 'img': img}) -
DRF: make a POST query without data
cannot manage a POST method-query to url /users/{pk}/subscribe Accesing this url should insert a record in db using Subscription model. No data is passed in body when accessing this url model.Subscription class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscriber', ) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscribing' ) a router to users router.register(r'users', CustomUserViewSet, basename='users') and the additional URL that accepts POST query in the CustomUserViewSet class CustomUserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = CreateUserSerializer @action( detail=True, methods=['post', 'delete'], permission_classes=[IsAuthenticated], ) def subscribe(self, request, *args, **kwargs): user = request.user author_pk = int(kwargs.get('pk')) author_to_subscribe = get_object_or_404(User, id=author_pk) if request.method == 'DELETE': return Response(status=status.HTTP_204_NO_CONTENT) if user.pk == author_pk: data = { "errors": "Cannot subscribe to yourself" } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) # q = Subscription.objects.filter(user=user) serializer = SubscriptionCreateSerializer(data=request.data) serializer.is_valid() serializer.save(user=user, author=author_to_subscribe) return Response( status=status.HTTP_200_OK) Method shoould return serialized data from another serializer (SubscriptionSerializer. So i have 2 serializer for subscription: for viewing and creating At this point in Postman getting error -
Django Rest Framework response give me datatype on M2M field
Working on a GET request from my django DRF backend, I receive a strange response from my m2m field. The response you see here is a response fetching from a Video model Array [ Object { "categories": Array [ "USA", ], "id": 1, "title": "first vid", }, Object { "categories": Array [ "other", ], "id": 2, "title": "second vid", ] Notice the "Object" and "Array" types in the response. Categories and Videos share a M2M relation related to the "categories" field The models: class CategoryVideos(models.Model): class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name class Videos(models.Model): category = models.ManyToManyField(CategoryVideos, null=True, blank=True) illustration = models.FileField(null=True, blank=True) video = models.FileField(null=True, blank=True) title = models.CharField(max_length=255, null=True, blank=True) The serializer: class VideoSerializer(serializers.ModelSerializer): categories = serializers.SerializerMethodField() class Meta: model = Videos fields = ["id", "title","categories"] depth=1 def get_categories(self, obj): companies = None try: companies = [obj.name for obj in obj.category.all()] except: pass return companies And the request, coming from Axios on a React Native app const fetchdata = async () => { const response = await axios.get( "https://some_ngrok_url/offerlist" ); const data = await response.data; const setnewdata = await SetData(data); }; fetchdata(); }, []); Can anyone spot the … -
How to convert django base user model date_joined to user local time
How i can convert the the date_joined field from base user model to logged in user local time? I want to get the local user time as i have tried to filter it by using time zone but no luck. -
Django - Querysets - Eficient way to get totals
I have to get totals for diferent type of concepts (Rem, NR, NROS, etc) in the queryset concepto_liq and I'm doing one filter for each type (see the code below), is there a way to make it more efficent? Thank in advance! tmp_value = concepto_liq.filter(tipo='Rem', empleado=empleado).aggregate(Sum('importe')) remuneracion = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) tmp_value = concepto_liq.filter(tipo='NR', empleado=empleado).aggregate(Sum('importe')) no_remunerativo = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) tmp_value = concepto_liq.filter(tipo='NROS', empleado=empleado).aggregate(Sum('importe')) no_remunerativo_os = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) tmp_value = concepto_liq.filter(tipo='ApJb', empleado=empleado).aggregate(Sum('importe')) aporte_jb = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) tmp_value = concepto_liq.filter(tipo='ApOS', empleado=empleado).aggregate(Sum('importe')) aporte_os = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100)