Multiplication cannot be performed on operands of type 'NoneType'

Hello everyone, I am attempting to calculate the unit price and quantity from this table using the following model:

class Marketers(models.Model):
    category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
    name =models.CharField(max_length=50, null=True, blank =True)
    grade =models.CharField(max_length=50, null=True, blank =True)
    quatity_received = models.IntegerField(default=0, null=True, blank =True)
    unit_price =models.IntegerField(default=0, null=True, blank =True)
    customer = models.CharField(max_length=50, null=True, blank =True)
    date_received = models.DateTimeField(auto_now_add=True)
    date_sold = models.DateTimeField(auto_now_add=True)

    @property
    def get_total(self):
        total = self.quatity_received * self.unit_price
        return total

This is how I call it in my template:

<td class="align-middle text-center">
  <span class="text-secondary text-xs font-weight-bold">{{ list.get_total }}</span>
  <p class="text-xs text-secondary mb-0">Overall Price </p>
</td>

This is the error I am encountering:

TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

Could someone please provide assistance? Thank you.

Answer №1

When dealing with nullable fields like quatity_received and unit_price, there is a chance of encountering an error when trying to multiply two NoneType values together.

TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

To illustrate the issue:

[3.8.8] >>> x=None
[3.8.8] >>> x
[3.8.8] >>> x*1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

Here's the Solution:

If you expect nullable fields, consider updating the get_total function as shown below:

@property
def get_total(self):
    if self.quatity_received is None and self.unit_price is None:
        return 0
    else:
        return self.quatity_received * self.unit_price

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to establish communication between Django and d3.js without a direct request?

I am currently facing a challenge with a django queryset that needs to be passed to d3.js for visualization purposes. My objective: - I have created a form that allows users to perform specific queries in my database (which is functioning correctly). ...

Troubleshooting Asynchronous Code in JavaScript

I was experimenting with creating a brute force poll voting script. $('#vote').click(function(e) { var votes = 0; var attempts = 0; var failures = 0; for(var i = 0; i < 500; i++){ ...

Conquering challenges arising from organizing subdirectories for js/css/xml files

During the process of developing a website with html, css, js and xml files stored on my computer (not yet online), I initially kept all the files in one folder along with an images folder. However, as the project progressed and things started to get mes ...

What is the best way to showcase a single <ul> list in an infinite number of columns?

Utilizing Django on the backend, I aim to showcase the list below in an unlimited number of columns with overflow-x: auto. <ul class="list"> {% for i in skills %} <li>{{i}}</li> {% endfor %} </ul> Example Result: 1 7 ...

no results returned from server request

The information variable is not returning the expected values of "OK" or "EXISTS". I've implemented a template with an overlay effect in income.html. The template includes a form and a button labeled "Add a new category". When the button is clicked, ...

Adjusting the URL variable based on the selected checkbox option

My mobile website offers users the option of a bright or dark interface using a checkbox styled like an iPhone IOS7 switch. The functionality is working as expected, but I'm now facing an issue with passing the status of the checkbox between pages. I ...

What could be causing issues with my jQuery POST call?

I am attempting to establish authentication with a remote service using jQuery. Initially, I confirmed that I can accomplish this outside of the browser: curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":" ...

Examining the contents of an array in JavaScript

I am currently conducting API testing. My objective is to verify the presence of a specific name within the API response. The data from the API response is structured in an array format. Despite my intention to check for the existence of the name "activ ...

Testimonials paired with captivating visuals

I am interested in featuring a rotating selection of testimonials on my homepage. I would like to display only one testimonial at a time, with the content randomized upon each page refresh. My vision is for each testimonial to include a quote, the author& ...

Allow AngularJS to make HTTP POST requests with CORS enabled

I am looking to submit a form to send an HTTP POST request to a server located on a different domain, with CORS enabled in the server script using Node.js. Below is the Angular configuration script: var myApp = angular.module('myApp', ['ng ...

What is the step-by-step process for incorporating the `module` module into a Vue project?

ERROR Compilation failed with 6 errors 16:20:36 This specific dependency could not be located: * module in ./node_modules/@eslint/ ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

Pull information from API and populate a dropdown menu in an Angular material select input

I am facing an issue with displaying data from an API in a mat select input field. I have tried to iterate over the data using a for loop but it is not working as expected. Can someone help me figure out how to properly populate the mat select input with d ...

Validating dates using JQuery within a specific range of dates

Users can input a date within a specified range in an input field. To enable this feature, I created a new method using the jQuery validator object: $.validator.addMethod("dateRange", function(value, element, from, to){ try { var date = new D ...

Tips for properly formatting a fixed table header

I'm currently facing an issue with the sticky header style in my data table. I have created a simple Angular component along with a specific directive: sticky.directive.ts @Directive({ selector: '[sticky]' }) export class StickyDirecti ...

Any ideas on how to extract binary data from PHP passthru using a JavaScript ajax request?

I am facing an issue with retrieving and playing an audio file from a server using JavaScript. The ajax call in my code doesn't seem to callback, and I'm not certain if I'm handling the audio correctly in JavaScript. Below is the PHP file t ...

Adding a Stripe pay button using Jquery append results in the return of an [object HTMLScriptElement

I'm currently working on dynamically adding the Stripe pay with card button through jQuery. I've decided to append it because I only want it to show up once a specific condition is met by the user, as well as due to the fact that the pricing can ...

What is the reason behind Q.js promises becoming asynchronous once they have been resolved?

Upon encountering the following code snippet: var deferred = Q.defer(); deferred.resolve(); var a = deferred.promise.then(function() { console.log(1); }); console.log(2); I am puzzled as to why I am seeing 2, then 1 in the console. Although I ...

Submitting forms using AJAX in Django

I am getting a 'Not Ajax' response every time I try to submit my form. There must be something small that I'm overlooking... class VideoLikeView(View): def post(self, request): if request.is_ajax(): message = 'Aj ...

AngularJS offers a single checkbox that allows users to select or

For my code, I need to implement a single checkbox. In my doc.ejs file: <tr ng-repeat="folder_l in folderlist | orderBy:created_date" > <td> <div class="permit"> <input class="chkbtn move_check" type="checkbox" id=" ...