Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How can i modify text before save them to database?

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
like image 335
fronthem Avatar asked May 27 '14 11:05

fronthem


People also ask

What does save () do in Django?

To save changes to an object that's already in the database, use save() . This performs an UPDATE SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() .

How do I save changes in Django model?

save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database. update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.

What is super save Django?

When you overwrite a function (of a class) you can call the function of the parent class using super . The save function in the models records the instance in the database. The first super(Review, self). save() is to obtain an id since it is generated automatically when an instance is saved in the database.


1 Answers

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)
like image 71
dhana Avatar answered Sep 20 '22 21:09

dhana