8

Is there any way to do in django custom property setter like this?

class MyModel(models.Model):
    myfield = models.CharField(length = 250)

    @myfield.setter
    def set_password(self, value):
       self.password = encrypt(value)
Nikolay Fominyh
  • 8,946
  • 8
  • 66
  • 102
  • 1
    this article by James Benett gives you a good idea on howto http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/ – Hedde van der Heide Oct 27 '11 at 08:04
  • related/ dupe: http://stackoverflow.com/questions/2898711/django-model-fields-getter-setter#11108157 – Matt May 13 '16 at 18:39
  • Possible duplicate of [Django model fields getter / setter](https://stackoverflow.com/questions/2898711/django-model-fields-getter-setter) – esmail Mar 15 '19 at 13:10

2 Answers2

1

You will really set the value on saving the model, so it's better to override save() method (ot use pre_save signal).

DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
1

What's wrong with a method?

instance.set_password('my_pw')

You can use @property to define setters: http://docs.python.org/library/functions.html#property

### Pasted from docs

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245