Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax and Python - How to deal with request timeout
I have a little django project that creates a XLSX report using XlsxWriter getting records from a database using the following "pseudo" python code: global myWorkbook myWorkbook = Workbook("my_report.xlsx", {'constant_memory':true}) db_conn = databases.getDbConnection() table1_thread = threading.Thread(target=generate_sheet, args=("table1", db_conn)) table1_thread.start() table2_thread = threading.Thread(target=generate_sheet, args=("table2", db_conn)) table2_thread.start() table3_thread = threading.Thread(target=generate_sheet, args=("table3", db_conn)) table3_thread.start() table4_thread = threading.Thread(target=generate_sheet, args=("table4", db_conn)) table4_thread.start() #Threads joining here... db_conn.close() return myWorkbook These tables that I'm doing the SELECT's are really huge (about 50 thousand rows) and takes a long time to generate the report (from 2 to 8 minutes). In my front end I want to use an ajax request to start the report generation and to show a "Download button" when the report is done in ajax success function. But I'm facing a timeout issue after the click on "Generate Report" button. I searched the Internet and I figure out that I can't change this ajax timeout. So, I would like to now: What should I do to accomplish this objective? I don't have the possibility to save the reports in the server because they are heavy (about 40~60MB) and it's generated every day. -
Django Qeryset order by a not directly related model's field
I have the following model design: class Boat(models.Model): name = models.CharField(max_length=30, null=False) harbour = models.ForeignKey(Harbour, null=True, on_delete=models.SET_NULL) class Harbour(models.Model): name = models.CharField(max_length=60) city = models.ForeignKey(City, null=True, related_name='city_harbours', on_delete=models.SET_NULL) class City(models.Model): name = models.CharField(max_length=80) county = models.CharField(max_length=30, null=True) class NearestCity(models.Model): city = models.ForeignKey(City, related_name='city', null=False, on_delete=models.CASCADE) near_city = models.ForeignKey(City, related_name='near_city', null=False, on_delete=models.CASCADE) weight = models.DecimalField(null=False, max_digits=25, decimal_places=20) Brief explanation: A Boat belongs to a Harbour and a Harbour belongs to a City. Not all Cities have a harbour related. NearestCity is a table where is stored how close is a city the rest of the cities: The weight is a decimal value that indicates how far is city from _near_city_ . The more smaller is the 'weight' value, the more close is city to near_city. For example: city near_city weight ---- --------- ------ London Rome 2.210103 London Manchester 0.113134 It means that Manchester is closer to Lonon than Rome. Problem to solve: Given a name of a city without any harbour related, for instance Berlin, a want to return all the boats of those closest cities that do have at least one harbour related. This Boat's queryset must be ordered by weight DESC. -
Using Django Templates to send an email
I have a Django template that I'm using to send emails. I'm using Sorl thumbnail to generate a thumbnail to be used in the email. {% thumbnail event.image '90x100' crop=True as im %} <img class="float-center" src="{{ im.url }}" alt=""> {% endthumbnail %} The issue is the src is an absolute path on the filesystem. I would like to prepend the im.url with my server's web address. I tried a few ways of concatenating strings but nothing seemed to stick. -
Django - How to call a @classmethod from a View as a result of form POST
I'm fairly new to Django and I'm not sure this is the best way to do this. To summarize- what I am trying to accomplish is: Call a @classmethod located within a ModelForm from the POST method within the TemplateView. Please see below for the pertinent code: form.py class bdForm(forms.ModelForm): addbdteam = forms.ModelMultipleChoiceField(queryset=TeamMember.objects.all().order_by('lastname'), widget=Select2MultipleWidget, required=False) @classmethod def assign_team(cls, addbdteam): for b in addbdteam: assignee = Broker.objects.filter(fullname=b) assignee.projects.add(cls) print('Added project to {}.').format(assignee) views.py class bdFormView(TemplateView): def post(self, request): form = bdForm(request.POST) if form.is_valid(): print("form is valid") project = form.save(commit=False) form.assign_team(form.cleaned_data['addbdteam']) # project.save() text = form.cleaned_data['briefcard'] brokername = form.cleaned_data['sourcingbroker'] brokerobj = Broker.objects.all().filter(fullname=brokername) print(brokerobj) Thanks for your help!! -
Django template not found although it it exists in templates folder
Django version 2.2.6 I have the following folder structure and was expecting Django to find index.html based as it is placed in the default location under templates. Am I doing something wrong here? Did Django stop looking up the template paths by default? -app | settings.py urls.py ... templates | base.html index.html views.py from django.shortcuts import render # Create your views here. def home_view(request): return render(request, 'index.html') urls.py from django.contrib import admin from django.urls import path from .views import home_view urlpatterns = [ path('', home_view, name='index'), path('admin/', admin.site.urls), ] -
Content Duplication when Extending CKAN with a custom theme
So I am trying to extend CKAN using our theme and I keep encountering issues due to plugin order (I believe) and content duplication. For example in 2 instances, I am trying to fix a missing font-awesome ICON in the Issues tab and rename Groups to Collections. The template file is ckan/templates/package/read_base.html and I am trying to override in dmt_theme/templates/package/read_base.html The following Screenshots and code output: {% ckan_extends %} {% block package_organization %} {% endblock %} {% block content_primary_nav %} {{ super() }} {% if h.issues_enabled(pkg) %} {{ h.build_nav_icon('issues_dataset', _('Issues'), dataset_id=pkg.name) }} {% endif %} {% endblock %} Produces this: And when I try to copy the content from CKAN's read_base.html file to just rewrite and control the whole block of content... And regardless of where I put the plugins in my development.ini file it seems to have the same effect. The plugin order is another issue I been battling for the better part of a year now. -
Django admin sites request
I am serving my webpage with nginx and waitress using https. When I go to my domain, I see the admin page, but when I try to login the following message appears: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Referer checking failed - https://example.com/admin/login/?next=/admin/ does not match any trusted origins. There are other threads around this topic, but all of them seem to address custom forms. This is the django default admin login page. How am I supposed to change the provided forms so that the CSRF tokens are sent? And why is this not happening automatically by default? My MIDDLEWARE list in settings.py contains django.middleware.csrf.CsrfViewMiddleware. -
Django, display part of table items in droplist in UpdateView class
I'm new to django. So I got two model class: 1. Order model, dealing with order details, including a "status_id" as FK related with Status table 2. Status model, storing order status, the scheme is something like below: id name 1 submitted 2 cancelled 3 pending 4 confirmed 5 completed The scenario is when customer created a order, status_id=1 (submitted) by default, who can also change the status to cancelled to cancel the order. Then only system admin can change the status to "pending", "confirmed" or "completed" depending on situations. So, on the page that admin manage orders, I want the dropdown list of status only show id=3,4,5 in Status table. How can I make that happen? By the way, I'm using generic class-basd view. Check the code below. Views.py class UpdateByAdminView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order fields = ['title', 'content', 'status'] def form_valid(self, form): return super().form_valid(form) def test_func(self): if self.request.user.is_staff: return True return False -
Django ModelForm Not Saving - Tried 3 methods of interacting with the Model
The Goal I have a list of calls, the callqueue, loading into a form based on the Current Custom User's Extension. I need to load the first instance and then cycle through the calls when the form is saved. I have a variable called follow_up that's a datefield and if set to later than todays date, that client won't pull in the query listed below and should accomplish the goal of moving the queue along. Thing is, I can't seem to get the form to save. Query referenced earlier Client.objects.filter(follow_up__lte=date.today(), csr__extension=request.user.extension).order_by('-hot') The thing is, I can't get the form to save. I've been troubleshooting this problem for a couple of days at this point and I feel my face and keyboard becoming friends soon. What I've tried so far Using a ModelForm with a Class Based View Using a ModelForm with an UpdateView Using a manually defined ClientForm(forms.Form) Making sure null= True, blank = True for testing purposes Using Pagination on a formset with one form limiting and specifying one form as found here def client_view(request): def wait_days(num): return timezone.now() + timezone.timedelta(days=num) wait_time = wait_days(2) FormSet = modelformset_factory(Client, form=ClientSheet, extra=0) if request.method == 'POST': formset = FormSet(request.POST) if formset.is_valid(): if … -
Make multiple POST requests to a URL concurrently in Python
I'm using Django and Django Rest Framework. Inside my urls.py, I've defined the following endpoint /payments/. It supports POST requests. Background info: Not long ago, we had a user send multiple requests to this server concurrently triggering a race condition and therefore stealing money. Question: How can I write a test to send 100-1000 requests to this URL API endpoint? This is how I currently send POST "test" requests in my test file: class PaymentViewTestCase(BaseTestCase): def setUp(self): super(PaymentViewTestCase, self).setUp() self.client = APIClient() self.client.force_authenticate(user=self.profile) def test_post_create_payment(self): amount = 1000 request_data = { 'amount': amount, } res = self.client.post( '/v2/instant/transfer/', ujson.dumps(request_data), content_type='application/json', secure=True ) However, I would like to trigger this POST request 1000, exactly at the same time. -
Save data into mysql with Django
I'm beginner with Django and I'm trying implement a app to save some data into Mysql 1st Step: I'm Check If "mag_no" field exist in mysql db, if yes: bring model_code and line_nm After that, I want create a form to include the other fields: CN1,CN2,CN3,CN4 and reuse the previous already get from first check. CN_form.html <form action="{% url 'CnCreateListMag' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Mag No:</label> <input id="mag_no" type="text" name="mag_no" value="{{ mag_no }}"> <label>Model Code:</label> <input id="model_code" type="text" name="model_code" value="{{ model_code }}"> <label>Line:</label> <input id="line_nm" type="text" name="line_nm" value="{{ line_nm }}"> <label>Result:</label> {% if result == 'OK' %} <a STYLE="background-color:DodgerBlue;">{{ result }}</a> <br><br> <form action="{% url 'magazine_new_add' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Mag No:</label> <input id="mag_no1" type="text" name="mag_no1" value="{{ mag_no }}"> <label>Model Code:</label> <input id="model_code1" type="text" name="model_code1" value="{{ model_code }}"> <label>Line:</label> <input id="line_nm1" type="text" name="line_nm1" value="{{ line_nm }}"> <label>CN1:</label> <input id="cn1" type="text" name="cn1" value=""> <label>CN2:</label> <input id="cn2" type="text" name="cn2" value=""> <label>CN3:</label> <input id="cn3" type="text" name="cn3" value=""> <label>CN4:</label> <input id="cn4" type="text" name="cn4" value=""> <button type="submit" class="btn btn-info my-4 btn-block">Save</button> </form> {% else %} <a STYLE="background-color:Salmon;">{{ result }}</a> {% endif %} <button type="submit" class="btn btn-info my-4 btn-block">Search</button> </form> My Views: @login_required def CnCreateListMag(request): form = CNForm(request.POST or None) if request.method … -
should I use Instagram postgressql id generator techniques for my project
If my epoch time is the 2019-11-11. For how many years can I generate unique I'd using Instagram technique. Can someone explain how this algorithm works. https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c?gi=a23b1b9c6107 -
Django: Limit the number of selections in the UI using the FilteredSelectMultiple Widget
I am using the FilteredSelectMultiple widget from Django Admin. My form currently looks something like this (I have changes some names for SO but it is functional): class SelectExampleForm(forms.Form): class Media: css = {'all': ('/static/widgets.css',), } js = ('/static/jsi18n.js',) def __init__(self, *args, **kwargs): group_name = kwargs.pop('group_name') location = kwargs.pop('location') r = super(SelectExampleForm, self).__init__( *args, **kwargs) # total pool of choices qs = Employee.objects.filter( group__name=group_name, town=location ) # Currently selected choices current = Employee.objects.filter( group__name=group_name, town=location, attendance__isnull=False ) # populating the widget ... self.fields['personnel'] = \ forms.ModelMultipleChoiceField( queryset=qs, widget=FilteredSelectMultiple( 'Employee', is_stacked=False), label='', initial=current, show_hidden_initial=True ) return r Although the details of the models aren't important it may help give some context: I have a current set of choices. There is a pool of potential choices that a user can select from. A quota of total selections allowed. This number is less than the number of potential choices. I would like to limit the number of choices one can select in the UI, so that only a certain number of choices n can be selected and appear on the right hand side of the widget. I am currently validating this on submission of the form, which I will continue to do, but … -
Django - testing emails with the outbox using post_office
I'm writing tests for an application that uses django-post_office package for most of its email functionality. The default django.core.mail library contains plenty of useful tools for testing whether or not there are actually emails being sent. (Without actually sending any during the tests) class TestFunctionThatSendsEmail(Testcase): @override_settings( EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend' ) def test_function_sends_email(self): self.assertEqual(len(outbox), 0) run_function_that_calls_email() self.assertEqual(len(outbox), 1) ... # other tests However, the emails in our function are being sent with the django-post_office mail.send() function # priority now to make sure that they are being sent right away mail.send( sender=sender, recipients=to, context=context, template=template_name, priority='now', ) Which causes the test above to fail as for some reason the emails do not end up in the outbox. The strange thing is that if I change the EMAIL_BACKEND to django.core.mail.backends.console.EmailBackend the emails do show up in my terminal, so it is listening to the EMAIL_BACKEND settings. I've tried finding alternative methods / functions to test this functionality in the django-post_office github, but all I could find was the advice to check to see if the emails are saved to the database and verify their status. (Which I did and works) but the fact that django seems to be unable to detect any emails actually being … -
Django nginx looking at static not staticfiles
I can't work this out, nginx insists on looking in a "static" folder even though I think I have given "staticfiles" as the location. Yet the logs are constantly showing the work "static" in the file path. Here is the nginx.conf: server { listen 80; server_name 10.88.58.95; location = /favicon.ico { access_log off; log_not_found off; } root /srv/pcc_django/; location /staticfiles/ { } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/gunicorn.sock; } } This is what the access logs are showing: 10.184.52.12 - - [18/Oct/2019:12:58:58 +0000] "GET /static/css/microblog/style.css HTTP/1.1" 404 77 "http://10.88.58.95/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 - - [18/Oct/2019:12:58:58 +0000] "GET /static/images/microblog/platform_control.png HTTP/1.1" 404 77 "http://10.88.58.95/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 - - [18/Oct/2019:13:03:58 +0000] "GET / HTTP/1.1" 200 5916 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 - - [18/Oct/2019:13:03:58 +0000] "GET /static/css/microblog/style.css HTTP/1.1" 404 77 "http://10.88.58.95/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 - - [18/Oct/2019:13:03:58 +0000] "GET /static/images/microblog/platform_control.png HTTP/1.1" 404 77 "http://10.88.58.95/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 … -
Django authentication JWT vs Oauth2
I am new in django authentication system. I notice most of the company and developer always prefer Oauth2 over JWT based authentication. I just read Oauth2 documentation. I am not getting what special feature in Oauth2 has and why Oauth2 is very cool Can anyone explain it please? -
django permissions: User should only see and edit "his" objects
I'm building an app to manage flats: There are different administrations. Each administration has users. Every administrations owns properties and every property has 1 to n flats. Sofar so good. That's more or less setup. No comes the tricky part. The users of administration A should only be allowed to see properties and flats that their administration owns. How would I best do this? -
How to add executable to PATH in Azure KUDU?
I need to add the gecko driver in order to run a headless browser on Azure as part of my website, but I need to add the geckodriver to PATH (apparently I can't manually input the location of the geckodriver file in Python?) I know I have to use the applicatioHhost.xdt file and add it to /home/site folder, but my Kudu page doesn't allow me to add files (I can create the file using 'touch', but I can't edit it). This is how my Kudu page looks like: https://imgur.com/a/99oHUoC This is my applicationHost.xdt: <?xml version="1.0"?> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <system.webServer> <runtime xdt:Transform="InsertIfMissing"> <environmentVariables xdt:Transform="InsertIfMissing"> <add name="geckodriver" value="geckodriverL" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" /> <add name="PATH" value="%PATH%;%HOME%\site\wwwroot\cpu" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" /> </environmentVariables> </runtime> </system.webServer> </configuration> This is the error I get from Django: WebDriverException at / Message: 'geckodriverL' executable needs to be in PATH. Request Method: GET Request URL: http://magicpcscout.azurewebsites.net/ Django Version: 2.2.6 Exception Type: WebDriverException Exception Value: Message: 'geckodriverL' executable needs to be in PATH. Exception Location: /antenv/lib/python3.7/site-packages/selenium/webdriver/common/service.py in start, line 83 Python Executable: /opt/python/3.7.4/bin/python3.7 Python Version: 3.7.4 Python Path: ['/opt/python/3.7.4/bin', '/home/site/wwwroot', '/antenv/lib/python3.7/site-packages', '/opt/python/3.7.4/lib/python37.zip', '/opt/python/3.7.4/lib/python3.7', '/opt/python/3.7.4/lib/python3.7/lib-dynload', '/opt/python/3.7.4/lib/python3.7/site-packages'] Server time: Fri, 18 Oct 2019 14:39:59 +0000 -
How can I make datetime.date more dynamic rather than manually entering a year?
I would like to make my code more dynamic by having a date use something like "next time it is August 1st". if form.cleaned_data['occurrence'] == 'weekly': start_date = tutor_session_form.cleaned_data['date'] while start_date < date(2020, 8, 1): MyModel.objects.create(form.cleaned_data['name'], date=start_date,) start_date += timedelta(days=7) else: form.save() So this works for what I want it to do, but I wouldn't want to manually have to change the year in the date every year, I'd prefer it to automatically use something that says "next time it is August 1st". I could use "current year + 1" but if this is used in February 2020 then it would make the condition August 1st 2021, when I would still want it to be 2020. Any help with this would be greatly appreciated! -
How to test answers to Django questions at stackoverflow
To all Djangonauts at stackoverflow: Due to the way django works a minimal working sample is usually big (view, model, url, ...). Therefore almost no question does provide such. This results in answers that cannot be good tested because some part of the code is missing. In my case it leads to answering almost only python questions because they're often testable. What is the best way to test django answers? Do you only use your experience or is there a trick for quick testing pieces of code (eg. a single view without knowing the model and urls? -
Django+MongoDB: Variable number of fields with django Model
I'm currently working with a django+python application using a mongoDB database. The objects in the collections in that database can have a variable number of attributes. What I'm wondering is if I would have to create a model field for every attribute and just deal with the fact that a large number of attributes are blank or if there is a method by which you can have a variable number of fields in a django Model or have the fields in an object dynamically generated instead of specified in the model (or if there is a package that allows that). This question was already answered for a SQL database being used with django here, but that didn't really tell me if the same was impossible for a django application with a mongodb database. Here is an example of some of the objects with variable fields that would be included in one collection. { 'id': 1, 'name': 'time', 'hat': 'top hat', 'shirt': 'dress shirt', 'vest': 'tweed', 'pants': 'black trousers', 'stopwatch': 'yes' }, { 'id': 2, 'name': 'James' }, { 'id': 3, 'pet': 'dragon' 'name': 'Ganilon' } What I'm hoping to find is something that dynamically generates the fields (or even just … -
Django Rest Framework Post nested models
I have three related models and I need to save all instances in a single transaction. A simplified version of my models are: class Recibosventas(models.Model): idreciboventa = models.AutoField(primary_key=True) idemplea = models.ForeignKey(Empleados, models.DO_NOTHING, db_column='idemplea', blank=True, null=True) idempres = models.SmallIntegerField() categocompro = models.CharField(max_length=2) tipocompro = models.CharField(max_length=1) puntoventa = models.SmallIntegerField() numero = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'recibosventas' unique_together = (('idempres', 'categocompro', 'tipocompro', 'puntoventa', 'numero'),) class Fondos(models.Model): idfondo = models.AutoField(primary_key=True) idemplea = models.ForeignKey(Empleados, models.DO_NOTHING, db_column='idemplea', blank=True, null=True) idtipofondo = models.ForeignKey('Tiposfondo', models.DO_NOTHING, db_column='idtipofondo') idconcepfondo = models.ForeignKey(Conceptosfondos, models.DO_NOTHING, db_column='idconcepfondo') idreciboventa = models.ForeignKey('Recibosventas', models.DO_NOTHING, db_column='idreciboventa', related_name='fondoreciboventa', blank=True, null=True) class Meta: managed = True db_table = 'fondos' class Movimientosfondos(models.Model): idmovimifondo = models.AutoField(primary_key=True) idfondo = models.ForeignKey(Fondos, models.DO_NOTHING, db_column='idfondo', related_name='movimientosfondos', blank=True, null=True) iddispon = models.ForeignKey(Disponibilidades, models.DO_NOTHING, db_column='iddispon') class Meta: managed = True db_table = 'movimientosfondos' serializers.py: class MovimientosfondosSerializer(serializers.ModelSerializer): class Meta: model = Movimientosfondos fields='__all__' class FondosSerializer(serializers.ModelSerializer): movimientosfondos = MovimientosfondosSerializer(many=True) class Meta: model = Fondos fields='__all__' def create(self, validated_data): with transaction.atomic(): # Crear la instancia de pedidos de venta movimientosfondos_data = validated_data.pop('movimientosfondos') fondos = Fondos.objects.create(**validated_data) # crear cada instancia de movimientosfondos for movimientosfondos_data in movimientosfondos_data: movimientosfondos_data['idfondo'] = fondos Movimientosfondos.objects.create(**movimientosfondos_data) return fondos def update(self, instance, validated_data): with transaction.atomic(): # Crear la instancia de pedidos de venta movimientosfondos_data … -
How to use list of values in get method?
I have a template filter in Django that looks ugly and not very pythonic. Is there a way to combine all the get requests into a list? @register.filter(name='is_supervisor') def is_in_group(user): group = Group.objects.get(name="security supervisor") group1 = Group.objects.get(name="cage supervisor") group2 = Group.objects.get(name="casino supervisor") group3 = Group.objects.get(name="food bev supervisor") return True if group or group1 or group2 or group3 in user.groups.all() else False I tried using a Q filter for chaining them together but that did not work. -
Django: dynamically/programatically setting model fields
I am attempting to create tables with fields based on metadata declared on other classes. My current approach is a bit like this: metadata = { ... } class CustomModel(MyBaseModel): ... for key, info in metadata.items(): setattr(CustomModel, key, fieldFrom(info)) What currently happens is that the table is created and the fields declared in class included. BUT the fields included through setattr are not getting included in the migration, even tough they correctly appear in the class when inspecting with de debugger. Is there any magic that only work for fields declared “in-place”? (Ps: written on a small phone, Ill improve the question when possible) -
How to apply annotations for Sum() on multiple django models?
I have three django models: ProjectName,ProjectBudget and ProjectActualCost. ProjectName stores the project name (ie Project X). ProjectBudget stores the project_name(as a foreign key(FK)),budget_name and the total_budget and date for each budget. ie (Project X, Hotel,600),(Project X, Rental,500). '600' refers to $600. ProjectActualCost stores each cost as it is incurred(itemized costs) (ie Hotel: 100, Rental: 50, Food:100) and its date. So it stores the 'project_name'(as FK),'budget_name'(as FK),actual_used and date. ie (Project X,Hotel,100,10/03/2019),(Project X,Hotel,100,10/06/2019), (Project X,Rental,50,04/10/2019) I'm trying to render the 'Project Name', 'Budget Name','Total Budget', 'Total Used'and 'Difference' in an html table. Project Name', 'Budget Name','Total Budget', 'Total Used' are rendering correctly,but 'Difference' displays inflated amounts as shown below. Models: class ProjectName(models.Model): project_name = models.CharField('Name',max_length = 15,blank = False) def __str__(self): return self.project_name class ProjectBudget(models.Model): project_name = models.ForeignKey(ProjectName,on_delete = models.CASCADE, null = True) budget_name = models.CharField('Budget Name'max_length = 50 total_budget = models.DecimalField('Total Budget',max_digits = 9,decimal_places=2) def __str__(self): return self.budget_name class ProjectActualCost(models.Model): project_name = models.ForeignKey(ProjectName,on_delete = models.CASCADE, null = True) cost_description = models.ForeignKey(ProjectBudget,on_delete = models.CASCADE,null=True) actual_used = models.DecimalField('Actual Used',max_digits = 15,decimal_places = 2) Views: def budgetview(request,project_id): budget_items = ProjectBudget.objects.filter(project_name_id=project_id).annotate( actual_cost=Sum('projectactualcost__actual_used'), difference=Sum('total_budget')-Sum('projectactualcost__actual_used')) budget_template = "budget_view.html" context = {"budget_items":budget_items} return render(request,budget_template,context) budget_view.html: <table> <thead> <tr> <th>Project Name</th> <th>Budget Name</th> <th>Total Budget</th> <th>Total Used</th> <th>Difference</th> …