Reputation: 4908
When I save form with empty date
and date_added
fields in django-admin site then it saves empty values there. I want to save current time instead. Here's code:
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Event(models.Model):
def __str__(self):
return self.title
title = models.CharField(max_length=300)
date = models.DateField(default=datetime.date.today, blank=True, null=True)
date_added = models.DateTimeField(default=timezone.localtime, blank=True, null=True)
text = models.TextField()
class EventPhoto(models.Model):
event_id = models.ForeignKey(Event, on_delete=models.CASCADE)
photo = models.ImageField(upload_to='news/')
Why default=timezone.localtime
doesn't work?
Upvotes: 0
Views: 5454
Reputation: 4908
I've figured out, that the problem is with django-admin. If I'll use code like this:
new_event = Event(title="blablah", text="some_text")
new_event.save()
then it saves DateField
properly using default=timezone.localtime
.
Probably django-admin tried to pass empty string to DateField
instead of not touching it and letting it take default action.
Upvotes: 0
Reputation: 47354
Django DateField
provides auto_now_add
and auto_now
arguments for this:
date = models.DateField(auto_now=True, blank=True, null=True)
date_added = models.DateTimeField(auto_now_add=True, blank=True, null=True)
Upvotes: 1
Reputation: 881
timezone.localtime
is a conversion function, not a value, and that's why it cannot be used.
Help on function localtime in module django.utils.timezone:
localtime(value, timezone=None)
Converts an aware datetime.datetime to local time.
Local time is defined by the current time zone, unless another time zone
is specified.
Upvotes: 0