简体   繁体   中英

Change rendering of a particular CharField in Django

I have a model BankAccount . BankAccount model contains CharField IBAN which is a International Bank Account Number. I use {{ bank_account.IBAN }} in multiple templates. It's stored as a string without spaces but I want to change it's template rendering such that every 4 characters are followed by zero.

SK121234123412341234 will be rendered as SK12 1234 1234 1234 1234

I could probably create some TemplateTag or TemplateFilter but I'm curious if there is a way to change it in BankAccount model. For example create my own IBANField (overriding CharField ) so I don't have to surrounding IBAN variable by tags or filters .

class BankAccount(models.Model):
    IBAN = models.CharField(max_length=40, ... )
    ...

Didn't find rendering methods here: https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/

You could create a custom field, but the easiest thing is just to write a method that displays the value in the right format. Something like:

class BankAccount(models.Model):
    ..
    def display_iban(self):
        return ''.join(l + ' ' if (i+1) % 4 == 0 else l for i, l in enumerate(self.IBAN))

and now you can do {{ bank_account.display_iban }} in the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM