Changing the admin edit window display values

Posted by Henri on Stack Overflow See other posts from Stack Overflow or by Henri
Published on 2010-04-13T15:07:30Z Indexed on 2010/04/13 15:43 UTC
Read the original article Hit count: 383

Filed under:
|
|

I have a database table with e.g. a weight value e.g.

CREATE TABLE product (
    id SERIAL  NOT NULL,
    product_name item_name  NOT NULL,
    .
    .

    weight NUMERIC(7,3), -- the weight in kg
    .
    .
    CONSTRAINT PK_product PRIMARY KEY (id)
);

This results is the model:

class Product(models.Model):
    .
    weight = models.DecimalField(max_digits=7, decimal_places=3, blank=True, null=True)
    .

I store the weight in kg's, i.e. 1 kg is stores as 1, 0.1 kg or 100g is stored as 0.1

To make it easier for the user, I display the weight in the Admin list display in grams by specifying:

def show_weight(self):
    if self.weight:
        weight_in_g = self.weight * 1000
        return '%0f' % weight_in_g

So if a product weighs e.g. 0.5 kg and is stored in the database as such, the admin list display shows 500

Is there also a way to alter the number shown in the 'Change product' window. This window now shows the value extracted from the database, i.e. 0.5. This will confuse a user when I tell him with the help_text to enter the number in g, while seeing the number of kgs.

Before saving the product I override save as follows:

def save(self):
    if self.weight:
        self.weight = self.weight / 1000

This converts the number entered in grams to kgs.

© Stack Overflow or respective owner

Related posts about django

Related posts about admin