0

My code is as follows...

class Todo(models.Model):
    state_choice = (('To Do','To Do'),('Doing','Doing'),('Done','Done'))

    def get_color_depends_state(self):
      if self.state:
         if self.state == 'To Do':
             self.color_code = '87CEEB'
         elif self.state == 'Doing':
            self.color_code = '7D3C98'
         elif self.state == 'Done':
            self.color_code = '00FF7F'  


    state = models.CharField(max_length=200,choices=state_choice,default='todo')

    color_code = models.CharField(max_length=6, default=self.get_color_depends_state)

My field color_code depends on the values of state field. I am trying to call the function from the color_code field but it is giving errors like self not defined or module has no attribute get_color_depends_state.

How I can call an instance method from field which intern depends on other field values(Here state)

Akhil Mathew
  • 1,571
  • 3
  • 34
  • 69
  • 1
    Your ``default='todo'`` in the state so wouldn't it make sense to default color_code to ``'87CEEB'``, which is the default for todo?. Also, I think your ``deafult = 'todo'`` should be changed to ``default='TO DO'`` – AspiringMat Feb 22 '17 at 12:32

2 Answers2

3

You can't do this in the default attribute, and it doesn't make sense to do so anyway as that is applied when the model is instantiated - so all the other fields would be blank as well.

Instead you should override the save method and do this logic there, checking that the field is blank and setting it to the default if so.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

You can do something like this:

class Todo(models.Model):
  state_choice = (('To Do', 'To Do'), ('Doing', 'Doing'), ('Done', 'Done'))

  state = models.CharField(max_length=200, choices=state_choice, default='todo')

  color_code = models.CharField(max_length=6)

  def get_color_depends_state(self):
     if self.state:
        if self.state == 'To Do':
           self.color_code = '87CEEB'
        elif self.state == 'Doing':
           self.color_code = '7D3C98'
        elif self.state == 'Done':
           self.color_code = '00FF7F'

  def save(self, *args):
    self.get_color_depends_state()
    super(Todo, self).save(*args)
Foon
  • 6,148
  • 11
  • 40
  • 42
Pankhuri Agarwal
  • 764
  • 3
  • 23