Reputation: 1133
I have Django version 1.4.5
Here are the relevant parts of my model
class Product (models.Model):
name=models.CharField(max_length=200)
description=models.TextField()
label=models.ForeignKey('Label')
pub_date = models.DateTimeField(editable=False)
def save(self):
#item will not have id if this is the first save
if not self.id:
self.pub_date = datetime.date.today()
super(Product, self).save()
def __unicode__(self):
return self.name
class Label(models.Model):
"""
A clothing label, e.g. Kate Spade
"""
name=models.CharField(max_length=100)
def __unicode__(self):
return self.name
When I attempt to publish a Product, selecting a Label works fine. Publishing the item works as expected, and the label field remains populated upon returning to the Product in the admin console. However, if I attempt to change the value of the label field, I am taken to the default list of Products page, with the message "he product "Prod 1" was changed successfully" but returning to the Prod 1 page reveals that the field wasn't actually saved properly.
Any ideas here?
Upvotes: 0
Views: 1016
Reputation: 7740
In your case, no need to set the date & time explicitly. You can use 'auto_now_add
' Please fer this link for more details.
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateField.auto_now_add
class Product (models.Model):
name=models.CharField(max_length=200)
description=models.TextField()
label=models.ForeignKey('Label')
pub_date = models.DateTimeField(editable=False, auto_now_add = True)
def __unicode__(self):
return self.name
If you need to set it manually, Use the following snippet. It calls super class for change also.
def save(self):
#item will not have id if this is the first save
if not self.id:
self.pub_date = datetime.date.today()
super(Product, self).save()
Upvotes: 1
Reputation: 4839
super(Product, self).save()
is within the if
block, so it isn't being called on edits. Also, why not just use auto_now_add
on the pub_date
field?
Upvotes: 1