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

Steps to Incorporate jQuery Function in a Partial View Inside a Modal

My jquery button click method is functioning correctly in views outside of modals, but the uploadbtn button click method does not work when a partial view is loaded in the modals. <script src="~/lib/jquery/dist/jquery.min.js"></script> ...

Exploring the functionality of a dynamic array in Vue.js 3

In my Vue.js 3 (beta) project, I have created an array using the reactive function in order to bind its items to various UI components through a loop. This setup has been successful thus far. However, I now face the challenge of updating a specific value ...

Are non-local variables in Node.js considered safe to use?

Would it be secure to implement this code in Node.js/Express.js? // using Object.create(null) to avoid key collisions // refer http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ var theHash = Object.create(null); exports.store = function (req, ...

What could be causing the incorrect updating of React State when passing my function to useState?

Currently, I am in the process of implementing a feature to toggle checkboxes and have encountered two inquiries. I have a checkbox component as well as a parent component responsible for managing the checkboxes' behavior. The issue arises when utiliz ...

Determining Velocity of an Object in Three.js

Can anyone help me figure out how to calculate an object's velocity in three.js? I've checked the Object3D documentation but can't seem to find anything related to velocity. Appreciate any assistance, ...

The inclusion of float: left disrupts the formatting of the list

My webpage features a visual element known as a "plan", which consists of a small table and an image. I want these two elements to appear side by side without any styling. Currently, they are displayed one below the other. You can view how it looks like he ...

Animating text with a shake effect using JQuery

I am attempting to create a shake effect on my text input field when validation fails. While I have achieved the shake effect, I am unsure how to customize the default values for direction, distance, and times. Additionally, I believe there is an error i ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

Employ CSS flexbox and/or JavaScript for creating a customizable webpage

I am in the process of developing a basic IDE for an educational programming language that has similarities to Karel the Dog. One major issue I am encountering is creating the foundation HTML page. The IDE consists of 4 main areas: Toolbox (contains but ...

Is it possible to restrict the draggable area?

Looking at this JSFiddle example, there is a box that can be dragged around the body. But, is it feasible to restrict dragging only when the user clicks on the purple section identified by the id "head"? $(document).ready(function(){ $( "#box" ).dra ...

Ways to resolve the issue of data-bs-target not functioning properly in Bootstrap version 5

While viewing the Job screen in the following image, I attempted to click on "Personal," but it remained stuck on the Job screen. ...

Update the content in the Bootstrap modal

I'm currently implementing modal Bootstrap in my ASP.NET website. I have encountered an issue where the text in the modal does not change according to the errors returned in the code behind, even after modifying the text value of the control before ma ...

Unusual Blank Space in HTML CSS Design

While working on my website, I noticed a peculiar white space appearing at the bottom of the page, but only when using Internet Explorer. Safari looks fine. I am currently using IE8. I would like the white background to end after the black navigation link ...

Preventing Bull Queue from automatically re-starting jobs upon server restart

Currently, I am utilizing the bull queue system for processing jobs. Imagine a scenario where a job is in progress with an active status and I restart my development server. Upon restarting the worker script, the job remains in the active state within the ...

Using Python and Selenium to retrieve information from the attribute 'data-label'

https://i.stack.imgur.com/zb7f5.jpg try: details = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "DataTables_Table_5")) ) scores_list = details.find_elements_by_tag_name('tbody') for sco ...

When defining multiple types for props in Vue, the default behavior for Boolean type props is not preserved

Imagine you have a component called MyComponent with a prop named myProp declared as: props: { myProp: Boolean } By simply using <MyComponent myProp/>, the default behavior would set myProp to true. However, this simplicity is lost when there ...

Is there a way to open a particular Bootstrap tab within a modal using a URL?

I am seeking a way to automatically open a specific tab within a modal using its URL. To achieve this, I have included the following JavaScript code at the end of my website. By entering website.com/#modal-6 in the browser, it will open with modal-6 activa ...

The issue of objects within objects consistently yielding undefined when using $.each

Maybe it sounds a bit silly, but I am dealing with this status JavaScript object containing other objects (output of console.log(status)): {1: {…}, 2: {…}, 10: {…}} 1: error: true __proto__: Object 2: validated: false value: 0 wh ...

Adjusting offcanvas height in Bootstrap based on content

.cursor-pointer { cursor: pointer; } <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="690b06061d1a1d1d09c13c809e9afbcfc1792efeff8">[email protected]</a>/dist/js/bootstr ...

Steps for Renewing Firebase Session Cookie

I am currently developing a web application utilizing Node.js/Express.js for the backend, with Firebase being used for user authentication. To manage user registration and other tasks, I rely on the Firebase Admin SDK. When a user attempts to log in, the ...