7

I want to input something like(via the admin page):

text = 't(es)t'

and save them as:

'test'

on database.

And I use this Regex to modify them:

re.sub(r'(.*)\({1}(.*)\){1}(.*)', r'\1\2\3', text)

I know how to transform text from 't(es)t' to 'test' but the problem is

when i use

name = models.CharField(primary_key=True, max_length=16)

to input text(from admin). It immediately save to database cannot modify it before saving.

Finally, From a single input from admin text = 't(es)t' (CharField).

What do i want?

  1. To use 't(es)t' as a string variable.
  2. Save 'test' to database
fronthem
  • 4,011
  • 8
  • 34
  • 55
  • possible duplicate of [Manipulating Data in Django's Admin Panel on Save](http://stackoverflow.com/questions/753704/manipulating-data-in-djangos-admin-panel-on-save) – Maxime Lorant May 27 '14 at 11:19

1 Answers1

19

Try to overide the save method in your model,

class Model(model.Model):
    name = models.CharField(primary_key=True, max_length=16)

    # This should touch before saving
    def save(self, *args, **kwargs):
        self.name = re.sub(r'(.*)\({1}(.*)\){1}(.*)', r'\1\2\3', self.name)
        super(Model, self).save(*args, **kwargs)

Update:

class Model(model.Model):
        name = models.CharField(primary_key=True, max_length=16)
        name_org = models.CharField(max_length=16)

        # This should touch before saving
        def save(self, *args, **kwargs):
            self.name = re.sub(r'(.*)\({1}(.*)\){1}(.*)', r'\1\2\3', self.name)
            self.name_org = self.name # original "t(es)t"
            super(Model, self).save(*args, **kwargs)
dhana
  • 6,487
  • 4
  • 40
  • 63
  • what should i do if i have another attributes below the `name`. Will `save` method affect to my another attributes? – fronthem May 27 '14 at 13:19
  • No it won't effects other attributes. It is customization of save method. If you want do anything before saving using this method. – dhana May 27 '14 at 14:17
  • Could i ask you one more question? How can i save the original text `t(es)t` to the variable is named `name_org` that i can use it later on this class? – fronthem May 27 '14 at 14:27
  • @terces907 I have updated my answer. If it is use please accept my answer. – dhana May 27 '14 at 14:33