Home > other >  How do I add a percentage field to a model in Django?
How do I add a percentage field to a model in Django?

Time:10-27

I don't know how to go about it in My models.py so basically, i want to be able to input a number let's say 5 in the form field or from the admin panel and it renders in out as 5%

I don't know if it's possible so what function do i use in my models.py did some research not helping help me out here.

My models.py is like this below

Username = models.Charfield(max_length=100)

Percentage = 

So that's where I'm stuck

CodePudding user response:

Django by default not have any percentage field but you can archive those things like this

models.py

from django.db import models


class ProductModel(models.Model):
    name= models.CharField(max_length=100)
    og_price = models.IntegerField(null=True, blank=True)
    sell_price = models.IntegerField(null=True, blank=True)
    discount = models.IntegerField(blank=True, default=0)
    discounted_price = models.IntegerField(blank=True, default=0)

    @property
    def discount_in_percentage(self):
        return f"{self.discount} %"

    @property
    def discounted_price(self):
        return ((self.og_price*self.discount)/100)

    @property
    def sell_price(self):
        return ((self.og_price - self.discounted_price))

admin.py

@admin.register(ProductModel)
class ProductModelAdmin(admin.ModelAdmin):
    list_display = ("discounted_price", "discount_in_percentage", "sell_price", "og_price", "name")[::-1]

in the admin panel Add the Product form

enter image description here

in the admin panel table display

enter image description here

  • Related