views:

31

answers:

2

Hey everyone,

Here is my problem. I have a model Project, that has a quote field in it. When a new instance of project is created I need to append the last 2 digits of the year plus a hyphen onto the start of the "quote" field. Ex. 2010 = "10-". Im just not quite sure how to start it?

As of right now I have hard coded in "10-" in as a pre-quote field, but I do not want to have to do that.

models.py

class Project(models.Model):
client = models.ForeignKey(Clients, related_name='projects')
created_by = models.ForeignKey(User, related_name='created_by')


#general information
proj_name = models.CharField(max_length=255, verbose_name='Project Name')
pre_quote = models.CharField(max_length=3,default='10-')
quote = models.IntegerField(max_length=10, verbose_name='Quote #', unique=True)
desc = models.TextField(verbose_name='Description')
starts_on = models.DateField(verbose_name='Start Date')
completed_on = models.DateField(verbose_name='Finished On')

Anyone have to do this before? Or have any suggestions?

A: 

Your existing quote field is set as an integer. You will need to set this as a text field. Once you do that, you can override the save() function to prepend "10-" to the field.

class Project(models.Model):
  client = models.ForeignKey(Clients, related_name='projects')
  created_by = models.ForeignKey(User, related_name='created_by')
  proj_name = models.CharField(max_length=255, verbose_name='Project Name')
  quote = models.TextField(max_length=10, verbose_name='Quote #', unique=True)
  desc = models.TextField(verbose_name='Description')
  starts_on = models.DateField(verbose_name='Start Date')
  completed_on = models.DateField(verbose_name='Finished On')

  def save(self):
    self.quote = "10-" + self.quote
Andrew Sledge
@Andrew I tried this, but when upon saving from form submit, I was presented with this:TypeError at /project/add/save() takes no arguments (1 given)
Steve
My apologies, updated code.
Andrew Sledge
+1  A: 

Try this:

def save(self):
    today = datetime.date.today()
    self.quote = "%s-%s" % (str(today.year)[2:4], self.quote)

Assuming you imported datetime.

kovshenin
I have imported datetime, but it is giving me this error: AttributeError at /project/add/'module' object has no attribute 'now'
Steve
Sorry for that, forgot `.date` in the middle.
kovshenin
Thank you, this is exactly what I was looking for.
Steve