Django - How can i modify text before save them to database?
database, django, python, regex, sqlite
Solution
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)
Problem
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? - To use `'t(es)t'` as a string variable. - Save `'test'` to database