2

Possible Duplicate:
(Django) Trim whitespaces from charField

In ruby on rails is really easy to strip spaces when saving a model. In django what's the best practice?

Community
  • 1
  • 1
tapioco123
  • 3,235
  • 10
  • 36
  • 42
  • 1
    Take a look at this answer, also here in StackOverflow: http://stackoverflow.com/questions/5043012/django-trim-whitespaces-from-charfield – Valdir Stumm Junior Aug 05 '12 at 14:05
  • I already saw that, I was hoping there is a more elegant way.... – tapioco123 Aug 05 '12 at 14:11
  • 1
    Or you could implement a new type of field to do it automatically – okm Aug 05 '12 at 14:22
  • https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#writing-a-field-subclass For creating your own field like okm suggested – dm03514 Aug 05 '12 at 14:25
  • There's no built in way to do this so you can do it the 'inelegant' way, or either write a custom ModelField or FormField depending on how you want to use it. – Timmy O'Mahony Aug 05 '12 at 14:54

1 Answers1

7

It is very easy to override models.Model save method, to perform any pre svae actions. The link that stummjr also provides an example.

class MyClass(models.Model):
    # some fields here

    def save(self, *args, **kwargs):
       # strip spaces here
       super(MyClass, self).save(*args, **kwargs)
       # make sure to call parent save method ^
okm
  • 23,575
  • 5
  • 83
  • 90
dm03514
  • 54,664
  • 18
  • 108
  • 145