Reputation: 111
Basically I have this code on my ModelForm:
def save(self):
if not self.instance.pk:
self.instance.author = self.author
self.instance.date_sorted = datetime.now()
return super(PostForm, self).save(commit = True)
My purpose it to only save date_sorted upon adding a record, and ignore it when editing. My date_sorted field is defined as:
date_sorted = models.DateTimeField(blank = True, null = True)
I defined blank=True and null=True on that because at some point I want some of the date_sorted to be null (on purpose).
When adding, the date_sorted will store the current date and time, but when editing (updating other fields), the date_sorted is changed to NULL. Tried to find similar issues on the net but no luck :(. Any help appreciated.
Upvotes: 0
Views: 908
Reputation: 1
models.DateTimeField
has two attributes: auto_now_add=True|False
and auto_now=True|False
.
Both of them will automatically make field as editable=False
.
Use auto_now=True
to set current date-time each time field is updated.
Use auto_now_add=True
to set current time only the first time object is saved.
Upvotes: 0
Reputation: 4364
Try this, it will hide datetime field from your form and automaticly set date when you post message:
date_sorted = models.DateTimeField(auto_now=True)
Also, you can use save_model method:
def save_model(self, request, obj, form, change):
super(MessageAdmin, self).save_model(request, obj, form, change)
I used this for admin panel and don't know how it works in other implementations, but try to look at it. You can type your code before saving object and after it, so you can modify obj.date_sorted and then save model.
Upvotes: 3