0

In a field of my Django model I want the user to type a dot ('.') at the end of a Textfield. Otherwise I want to add it.

I've thought about using a validator but it seems it's not the proper way to do it:

name = models.TextField(validators=[validate_dot])

def validate_dot(value):
    if value:
        if value[-1] != '.':
            return value + '.'

Whay I need is to change the value of the TextField (if required) not to raise an error.

What is the best approach to achieve it?

loar
  • 1,505
  • 1
  • 15
  • 34
  • Possible duplicate of [Is this the way to validate Django model fields?](http://stackoverflow.com/questions/12945339/is-this-the-way-to-validate-django-model-fields) – Sayse Jul 06 '16 at 10:18
  • How about doing it client-side, in the `onchange` method of the field or the `onsubmit` method of the form? This may have the extra advantage of the user actually seing the dot being added. – raphv Jul 06 '16 at 10:28
  • Since this value is goint to be saved in DB I prefer to check this issue in the server-side. In any case I could check it in the cliend side too. – loar Jul 06 '16 at 10:31

1 Answers1

0

You can override the save() method on your model.

def save(self, *args, **kwargs):
    if not self.name.endswith("."):
       self.name = self.name + "."
    super(Model, self).save(*args, **kwargs)
Siva Arunachalam
  • 7,582
  • 15
  • 79
  • 132