Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple distinct values queryset for SQLDB
I'm trying to get a list of results that have distinct x and y values, but I also want to return color along with them. Since I'm using an SQLDB I'm not allowed to use the fieldnames arg of distinct. Is there a good work around for this? All the examples I'm been looking up haven't been working out. The query that I'm not allowed to run: queryset = Tile.objects.values('x', 'y', 'color').distinct('x', 'y') -
Search functionality in list view
I am trying to implement search functionality in my CBV list view. To do that have I written a "get_queryset". The view looks like this class List(ListView): model = Client ... def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) query = self.request.GET.get('q') if query: return qs.get(user=query) return qs When I have it like this, I get the following error: "Field 'id' expected a number but got 'x'.". x is in this case whatever I inputed in the search field. But if I change user to something invalid, I get the following error: "Cannot resolve keyword '' into field. Choices are: user, user_id". I don't understand why user does not work in this case and why it uses the field "id" if I specify user. -
Django - file isn't being downloaded
I have a django app, with a vuejs frontend. I'm making a PUT request from my Vue front-end. As a response, I want a xlsx file to be generated & downloaded. For some reason, the file isn't being downloaded. Here's the generate & download function. def export_to_main(request): if request.method == 'PUT': response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'inline; filename="exported_to_main.xls"' selected_claims = Claim.objects.filter(status='PA') workbook = Workbook(encoding='utf-8') group_header_style = easyxf( "font: bold true; pattern: back-colour blue;") number_style = easyxf(num_format_str="#,##0.00") date_style = easyxf(num_format_str='DD-MM-YYYY') sheet = FitSheetWrapper(workbook.add_sheet("Sheet 1")) header_column = count() sheet.write(0, header_column.next(), 'Book Number', group_header_style) sheet.write(0, header_column.next(), 'Dossier', group_header_style) sheet.write(0, header_column.next(), 'Dossier Type', group_header_style) for i, claim in enumerate(selected_claims, 1): try: column = count() sheet.write(i, column.next(), claim.book_nr) sheet.write(i, column.next(), claim.kind) sheet.write(i, column.next(), getattr(claim.letter_claim_type, 'label')) except IndexError: print("error"*5) pass # selected_claims.update(status='AP', exported_to_main=datetime.datetime.now()) workbook.save(response) return response If I print(response) I get the workbook in my console. So the excel is generated properly. For some reason, it is not being downloaded on the frontend though. Here's the vue code: <v-row> <v-btn color="success" @click="exportMain" download > Export to main </v-btn> <v-spacer></v-spacer> <v-btn color="success" :href="xls"> Export Excel </v-btn> </v-row> and this method is being called on that button click: export_to_main({commit}) { const url = action="{% url 'control:export-to-main' %}" commit('set_loading', … -
API view returning { "detail": "Not found." },
class User(models.Model): user_id = models.CharField(max_length=255, unique=True) mobile = models.CharField(max_length=12) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) profile_image = models.URLField(null=True) email = models.EmailField(null=True) posts = models.ManyToManyField('uploads.Posts', related_name='post_user') created_on = models.DateTimeField(default=timezone.localtime) updated_on = models.DateTimeField(default=timezone.localtime) is_deleted = models.BooleanField(default=False) class Posts(models.Model): url = models.URLField(null=True) description = models.TextField() created_on = models.DateTimeField(default=timezone.localtime) updated_on = models.DateTimeField(default=timezone.localtime) is_deleted = models.BooleanField(default=False) These are my models, I have created a serializer for Posts and nested it under a UserPostSerializer. class PostSerializer(serializers.ModelSerializer): class Meta: model = Posts exclude = ('id', 'created_on', 'updated_on', 'is_deleted') class UserPostsSerializer(serializers.ModelSerializer): posts = PostSerializer(many=True) class Meta: model = User fields = ('user_id', 'profile_image', 'posts',) However, when I create a view like this- class UserPostsView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserPostsSerializer def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) response = Response(serializer.data) return response my API returns { "detail": "Not found." } Ideally, the view should list all the users along with their posts. Something like: { "user_id": "abcd", "url": "http:....com", "description": "Lorem ipsum" } -
FIle path is correct but still getting filenotfound error [Django]
I have written a small django project. Inside the project I am calling a different script to run. Example code below: cmd1 = 'python3 myscript.py' subprocess.Popen(cmd1) This works fine on my windows machine but when I run the same project on my linux machine, it shows error that No such file or directory exists I am not able to understand the cause of this error. Please help me fix this [The project was first built on windows that as it is copied from windows machine to linux machine] -
Custom field with special constrains in DRF serializer
I'm trying to add a custom field with some special constrains in DRF serializer. Following are 2 sample models: class ModelA(models.Model): field1 = models.CharField(max_length=200) field2 = models.CharField(max_length=200) field3 = models.CharField(max_length=200) class ModelB(models.Model): field4 = models.ForeignKey(ModelA, on_delete=models.CASCADE) field5 = models.CharField(max_length=200) What I want is a serializer based on ModelA, but with a custom field displaying a string combining field5s of all ModelB instances this ModelA instance has. I know this API design is a little bit weird, but based on the existing code base, we have to do it this way. Also I wanna this field to be writable, so SerializerMethodField doesn't work. I tried to follow the example here: https://www.django-rest-framework.org/api-guide/fields/#examples. But my case is a little bit different, since it involves multiple models. Some sample code would be very helpful! Thx! -
django websocket cannot send data to client after receiving it
class WSTestView(WebsocketConsumer): def connect(self): self.accept(); self.send(json.dumps({'status': 'sent'})) # client receives this def receive(self, text_data=None, bytes_data=None): notifications = Notification.objects.filter(receiver=text_data) # receives user id serializer = NotificationSerializer(notifications, many=True).data self.send(serializer) # client does not receives this Frontend // ... useEffect(() => { socket.onmessage = (e) => { console.log(e.data) } }, []) // ... I've just started with django-channels and am working on a consumer that sends the user's notifications when it receives the user's id but on the frontend the onmessage event does not receive anything, how can I fix this and is there a better way that I can implement this? -
Interogation and creation of sqlite table using django
I have some tables in my database and I want to combine somehow. The tables are about heartrate (data, hour:minutes, heartrate for that minute), other table sleep (start sleep, end sleep, etc.). I want to combine them and to know what is the heartrate in that interval of sleeping and after that to put the tag "sleeping" for that day, hour, heartrate. I don't know now if it make sense to create another table (date, hour, heartrate, tag) or to put that tag in the first table with heartrate. I want to mention that the values that I have in the tables are imported via django, so it will be added more values for different user there. The interrogation in the first table with the interval of sleeping from table 2, id did it with command join? Do you have some example of code in django for this? -
Redirect user from login to crud first page
I'm new in django and even in python I have a project 'mysite' with 3 apps. Configs of urls mysite urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), # user management path('account/', include('allauth.urls')), #local path("", include("pages.urls", namespace="pages")), path("imoveis/", include("imoveis.urls", namespace="imoveis")), ] App Users - no urls.py App Imoveis - urls.py: from django.urls import path from . import views app_name = "imoveis" urlpatterns = [ path('', views.form, name='form'), path('create/', views.create, name='create'), path('view/<int:pk>/', views.view, name='view'), path('edit/<int:pk>/', views.edit, name='edit'), path('update/<int:pk>/', views.update, name='update'), path('delete/<int:pk>/', views.delete, name='delete'), ] and App pages - urls.py: from django.urls import path from . import views app_name = "pages" urlpatterns = [ path("", views.HomePageView.as_view(), name="home"), ] I have a template folder (a folder not inside any app or project) with: Accounts Folder: login.html, logout.html and signup.html -Imoveis Folder: form.html, read.html and view.html and base.html and home.html direct in template folder I want to when user log in they goes to form.html. I don't know how to change from base.html I put in form.html : {% extends 'account_login.html' %} but nothing. Any help are welcome. Regards -
Django server doesn't serve requests
I've got a django server up and running. When I try to it any api in it, it gives error "Error: Parse Error: Expected HTTP/" on postman. I've tried to access a single api directly from browser by typing "localhost:9001/". I have a default health check api which should ideally run on this, but none of my apis are working on this. -
Django javascript online connection with socket?
Learning Django/socket, I challenged myself with a little online 1v1 memory card game. For the moment the code is able to create a landing page then creating/joining a room. The room present the memory card game with a chat. My following problem is that the memory card is not the same for the room, look like a random is generate 2 times even if player are in the same room If you have any clue, adivices I will appreciate. (not a pro or a student, just doing it for my pure enjoyement, sorry if the following code contains errors) Here is my code HTML : % extends 'base.html' %} {% load static %} {% block content %} <div class="container main"> <div class="sideme"> <div class=" w-100 d-flex justify-content-center"> <div> <strong class="my-3 text-white text-center"> <p class ="mt-3"id="userdiv"> </p> <span class="my-3">Total User : <span id="user_num"></span></span><br> <div class="d-flex justify-content-between"> <div><span id="userTurn"></span> Turn</div> <div id="lastStepDiv"> </div> </div> </strong> <div class="wrapper"> <ul class="cards"> <li class="card"> <div class="view front-view"> <img src="{% static 'images/que_icon.svg' %}" alt="icon"> </div> <div class="view back-view"> <img src="{% static 'images/img-1.png' %}" alt="card-img"> </div> </li> <li class="card"> <div class="view front-view"> <img src="{% static 'images/que_icon.svg' %}" alt="icon"> </div> <div class="view back-view"> <img src="{% static 'images/img-6.png' %}" … -
Django dynamic sitemap without using models
So, basically I have data coming from an API. There's no model and the data is not stored in my database. I just send request and get data. The problem is every single tutorial for dynamic sitemaps in Django requires usage of Models. Also came across this question but it doesn't have a proper solution. Is it possible to use Django's built-in sitemap module in this scenario or should I create my own script that generates sitemap programmatically? -
How to create url path dynamically from list of dicts
I have a list of dicts that contains a path, view, and view name suppose I have the following list with many of URLs, that are in the following format url_lsts = [ {"path" "preview/", "view": reverse("app:index"), name="preview"} ... ] urlpatterns = [ path(url["path"], url["view"], name=url["name"]) for url in url_lsts ] when using reverse i'm getting following url django.core.exceptions.ImproperlyConfigured: The included URLconf 'aisp.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I've tried reverse_lazyand got the following URL raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
How to display a line chart with Charts.js and Django?
I would like to display a line chart in my Django template with chart.js but I'm unable to display something, except variables labels and data. The data structure seems to be correct according to the documentation, what could cause the issue ? > labels ['Home'] > data [{'x': '2022-01-07 16:00:00', 'y': 1.0}, {'x': '2022-01-08 16:00:00', 'y': 1.01}, {'x': '2022-01-08 17:00:00', 'y': 1.05}] base.html <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"> </script> template.html {% extends "base_generic.html" %} {% load static %} {% block content %} {% block scripts %} <script> // jquery function $(document).ready(function(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: {{labels}}, datasets: [{ label: 'Home data', data: {{data}} }] } }); }); </script> {% endblock scripts %} <canvas id="myChart" width="400" height="100"></canvas> {% endblock %} -
how to change form field from dropdown list to radio button in django if the options in dropdown are being inherited from another model?
i am working on an application where i can select item from drop-down list and buy them. i have a form field which is a drop-down list(items are connected to other model via foreign key.i want to make those options appear as radio buttons instead of drop down list my models.py class Plans(models.Model): plan_name = models.CharField(max_length=50) speed = models.IntegerField() price = models.FloatField() def __str__(self): return self.plan_name def get_deadline(): return dt.today() + timedelta(days=30) class Orders(models.Model): user = models.ForeignKey(CustomUser, primary_key=True, on_delete = models.CASCADE) pack = models.ForeignKey(Plans, on_delete = models.CASCADE) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(default=get_deadline()) is_active = models.BooleanField(default=True) def __str__(self): name = str(self.user.username) return name def get_absolute_url(self): return reverse('home-home') my forms.py(i tried using the init method but my drop down list vanishes when i use it) class BuyPlanForm(forms.ModelForm): error_css_class = 'error-field' required_css_class = 'required-field' class Meta(): model = Orders fields = ['pack'] #def __init__(self, *args, **kwargs): # super(BuyPlanForm, self).__init__(*args, **kwargs) # for field in self.fields.values(): # if isinstance(field.widget, forms.Select): # field.widget = forms.RadioSelect() my views.py class UserBuyPlan(LoginRequiredMixin, CreateView): template_name = 'plans/plan.html' form_class = BuyPlanForm def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) please help.(sorry i tried my best to explain the problem i am having but my english isn't that great) -
Django many-to-many relations
I'm trying to create a web app in which users can participate in some groups (every user can be part of multiple groups), and I want to be able to make both queries like group.users_set() and user.groups_set() I want to see all groups a user is participating to in the admin page of every user and vice versa. My last attempt was this: class CustomUser(AbstractUser): groups = models.ManyToManyField('Group', through='Participation') class Group(models.Model): group_name = models.CharField(max_length=200) group_password = models.CharField(max_length=200) customusers = models.ManyToManyField('CustomUser', through='Participation') class Participation: customuser = models.ForeignKey(CustomUser, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) but I get django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'userreg.admin.CustomUserAdmin'>: (admin.E013) The value of 'fieldsets[2][1]["fields"]' cannot include the ManyToManyField 'groups', because that field manually specifies a relationship model. Before, with just users = models.ManyToManyField(CustomUser) in the Group class and without the Participation class, I was able to get half of my goal, seeing the list of logged users in the admin page. What am I doing wrong? -
I can't render through the foreign key
I have a doubt. I want to show a name(nombre) of each client (cliente) with the total amount of money owed, so that each record is in a different cell. In pycharm I have this written: presupuestos.html <tbody> {% for pago in pagos %} <tr> <td> {% for presupuesto in presupuestos %} {{presupuesto.cliente.nombre}} {% endfor %} </td> <td> {{pago.cantidad_pagada}} </td> </tr> {% endfor%} </tbody> What happens is that when rendering this: {% for presupuesto in presupuestos %} {{presupuesto.cliente.nombre}} {% endfor %} The name appears, which is what I want to show, the bad thing is that all the repeated names appear in the same cell. But when using this: {{pago.estimate.cliente.nombre}} Nothing appears and If I put {{pago.estimate}} 'none' appears, but if there was nothing in the next loop the names would not appear I do not understand if my problem is due to my view.py or my models, possibly it is due to "estimates" in my payment model but I do not understand how to change it to be able to access that value pagos/models.py class Pagos(models.Model): numero_transaccion=models.IntegerField() estimate=models.ForeignKey(Presupuestos, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.numero_transaccion}' presupuestos/models.py class Presupuestos(models.Model): cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.cliente}' clientes/models.py class Clientes(models.Model): nombre … -
How can I include reverse related items in s Django serializer?
I'm trying to add all Payments that relate to a PayrollRun in the serializer to also return this. But how would I basically add reverse relations to a serializer? # views.py class PayrollRun(APIView): """ Retrieve payroll runs including line items for a company """ def get(self, request): # Get the related company according to the logged in user company = Company.objects.get(userprofile__user=request.user) payroll_runs = Payroll.objects.filter(company=company) serializer = PayrollSerializer(payroll_runs, many=True) return Response(serializer.data) # models.py class Payroll(models.Model): """ A table to store monthly payroll run information of companies """ # Relates to one company company = models.ForeignKey(Company, on_delete=models.CASCADE) month = models.DateField() amount = models.DecimalField(decimal_places=2, max_digits=10) line_items = models.PositiveIntegerField() def __str__(self): return f'Payroll run month {self.month} for company {self.company.name}' class Payment(models.Model): """ A table to store all payments derived from an offer """ # Relations offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.ForeignKey(Period, on_delete=models.CASCADE) payroll_run = models.ForeignKey(Payroll, on_delete=models.CASCADE, null=True, blank=True) # is populated once the payroll run was created amount = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return f'{self.offer} with an amount of {self.amount} and payment month {self.month}' # serializers.py class PayrollSerializer(serializers.ModelSerializer): class Meta: model = Payroll depth = 1 fields = '__all__' right now returns the following without the related payment instances [ { "id": 12, … -
Put a book in several categories (Django)
I have a model named "book" and a model named "BookCategoty". how i can assign infinite category ForgienKeys? for books that fall into several categories. -
Django Rest Framework - Wrapping the JSON response with the name of the model
My goal is to customize the JSON response from Django DRF when listing items. The model: class Object(models.Model): code = models.CharField(max_length=16, primary_key=True, unique=True) item = models.CharField(max_digits=128) last_updated = models.DateTimeField(auto_now=True, editable=False) the serializer: class ObjectSerializer(serializers.ModelSerializer): class Meta: model = Object fields = ['code', 'item'] the view: class ObjectList(generics.ListAPIView): queryset = Object.objects.all() serializer_class = ObjectSerializer def list(self, request): queryset = self.get_queryset() serializer = ObjectSerializer(queryset, many=True) return Response(serializer.data) with this setup the JSON response is: [ { "code": "111", "item": "aaa" }, { "code": "222", "item": "bbb" } ] Is there a way to wrap the response with the name of the model? Expected result would be: "objects": [ { "code": "111", "item": "aaa" }, { "code": "222", "item": "bbb" } ] -
Save django Models in different script and run that script with HTML button
I have model.py as ''' class Fruit(models.Model): name = models.CharField(max_length=16) weight = models.IntegerField(max_length=16) color = models.CharField(max_length=16) class Veg(models.Model): name = models.CharField(max_length=16) weight = models.IntegerField(max_length=16) ''' I have myFunction.py as ''' def makeModels(file): with open(file, 'r') as f: line=f.readline() while line: if line.split(',')[0] == 'fruit': a = Fruit(name=line.split(',')[1], weight=line.split(',')[2], color=line.split(',')[3]) a.save() if line.split(',')[0] == 'veg': b = Veg(name = line.split(',')[1], weight = line.split(',')[2] b.save() line = f.readline() ''' and files as abc.txt "fruit,apple,3,red\n fruit,banana,1,green\n veg,spinach,4\n veg,collard,2\n fruit,banana,3,yelow\n veg,broccoli,3\n fruit,orange,1,orange" I want to create an HTML button to trigger this function/script and also create a celery scheduler to schedule a trigger to run at a time on a daily basis. This is on a django framework. Please help me on how to approach it. The running external function to save models through html button and scheduling it part. Thank you! -
django.db.utils.ProgrammingError:[SQL Server]The identifier that starts with xxx is too long. Maximum length is 128
I am trying to execute a store procedure using python. For that, I am passing json as input parameter of the stored proc. My json format is like: [ {"stored_procedur_root": {"sample11Id": 1050, "Userid": 1, "CreatedBy": 1388}}, {"stored_procedur_root": {"sample11Id": 1050, "Userid": 3, "CreatedBy": 1388}}, {"stored_procedur_root": {"sample11Id": 1050, "Userid": 6, "CreatedBy": 1388}} and so on.... ] If I execute the stored proc for only one row then the commit is successful but if I try multiple row input then I am getting error: django.db.utils.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The identifier that starts with '{"campaign_queue_users": {"CampaignId": 1050, "Userid": 1, "CreatedBy": 1388}}, {"campaign_queue_users": {"CampaignId": 1050, "U' is too long. Maximum length is 128. (103) (SQLExecDirectW)') What I believe is that I the query length exceeds 128 char limit after getting json input but I am unable to handle it. Is there a way that I can pass the json of list of dictionary line by line in the stored proc or I am doing wrong here? NOTE: I have tried single quote input also but getting the same error. Can someone please help me there, thanks in Advance. -
Filter related field Django orm shows multiple invalid results
Query TechnicianAssignment.objects.filter(Q(slot__slot_date=curr_datetime.date())&Q(assigned_technician__attendance_Technician__attendance_status__in=['Rejected', 'Absent', 'Someone else reported', 'Present'])) Models in short: **Table 1**: class TechnicianTeam(models.Model): id = models.AutoField(primary_key=True) supervisor = models.ForeignKey('self', null=True, blank=True, related_name="TechnicianSupervisor", on_delete=models.DO_NOTHING) customer_profile = models.ForeignKey('login.CustomerProfile', related_name="technician_TeamUser", on_delete=models.DO_NOTHING) class Meta: db_table = "technician_team" **Table2:** class TechnicianAssignment(models.Model): id = models.AutoField(primary_key=True) slot = models.ForeignKey('technician_management.TechnicianSlot', related_name="assignment_Slot", on_delete=models.DO_NOTHING) assigned_technician = models.ForeignKey('technician_management.TechnicianTeam', related_name="assignment_Technician", on_delete=models.DO_NOTHING) class Meta: db_table = "technician_assignment" **Table3** ATTENDANCE_CHOICES = [ ('Rejected','Rejected'), ('Someone else reported','Someone else reported'), ('Absent','Absent'), ('Present','Present') ] class TechnicianAttendance(models.Model): id = models.AutoField(primary_key=True) technician = models.ForeignKey('technician_management.TechnicianTeam', related_name="attendance_Technician", on_delete=models.DO_NOTHING) slot = models.ForeignKey('technician_management.TechnicianSlot', related_name="attendance_Slot", on_delete=models.DO_NOTHING) attendance_status = models.CharField(max_length=30, choices=ATTENDANCE_CHOICES, null=True) class Meta: db_table = "technician_attendance" Question what is wrong with my query: I need to filter out from TechnicianAssignment where in entries were "slot__slot_date" is current date and "__attendance_Technician__attendance_status__in" = ['Rejected', 'Absent', 'Someone else reported', 'Present'] there is only 1 entry in db with attendance status 'Present' but i am getting many output because of "__attendance_Technician__attendance_status__in" this filter. -
How to run Django admin site on Android
This is what am facing with with Django on my Android I'm using Pydroid on my phone. Python and Django are fully functional. But when I try to run Django admin site on Chrome it shows "Server error occurred. Contact administrator" and in the terminal it shows this error: storage/emulated/0/mysite $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 28, 2022 - 16:28:28 Django version 4.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C. [28/Apr/2022 16:28:45] "GET /admin/ HTTP/1.1" 302 0 [28/Apr/2022 16:28:55] "GET /admin/ HTTP/1.1" 302 0 Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/zoneinfo/_common.py", line 12, in load_tzdata return importlib.resources.open_binary(package_name, resource_name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 88, in open_binary package = _get_package(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 49, in _get_package module = _resolve(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 40, in _resolve return import_module(name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/__init__.py", line 127, in import_module 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 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line … -
Can't aggregate a DecimalField in Django
I have a queryset where I want to aggregate the fields amount which itself is a DecimalField. The target field is also a DecimalField. I get this error: django.core.exceptions.ValidationError: ["“{'amount__sum': Decimal('3821.02000000000')}” value must be a decimal number."] Why does it say it must be a decimal number even though it is a DecimalField? # models.py class Payment(models.Model): offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.ForeignKey(Period, on_delete=models.CASCADE) payroll_run = models.ForeignKey(Payroll, on_delete=models.CASCADE, null=True, blank=True) # is populated once the payroll run was created amount = models.DecimalField(decimal_places=2, max_digits=10) class Payroll(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) month = models.DateField() amount = models.DecimalField(decimal_places=2, max_digits=10) line_items = models.PositiveIntegerField() def test(): ... # Loop the companies for company in qs_companies: # Query all Payments of that company in that month qs_payments = Payment.objects.filter(offer__company=company).filter(month=period) # Create a payroll run instance payroll_run = Payroll.objects.create( company=company, month=next_payroll_run, amount=qs_payments.aggregate(Sum('amount')), line_items=qs_payments.count() ) payroll_run.save() ...