23👍
From the Django documents for Field.default
:
The default value for the field. This can be a value or a callable
object. If callable it will be called every time a new object is
created.
So do this:
from datetime import datetime, timedelta
def default_start_time():
now = datetime.now()
start = now.replace(hour=22, minute=0, second=0, microsecond=0)
return start if start > now else start + timedelta(days=1)
class Something(models.Model):
timestamp = models.DateTimeField(default=default_start_time)
18👍
in case you’re interested into setting default value to TimeField: https://code.djangoproject.com/ticket/6754
don’t:
start = models.TimeField(default='20:00')
do instead:
import datetime
start = models.TimeField(default=datetime.time(16, 00))
- [Django]-Django Admin: How to access the request object in admin.py, for list_display methods?
- [Django]-Django datetime issues (default=datetime.now())
- [Django]-Custom HTTP Header in Django
4👍
datetime.time(16, 00)
does not work.
Use datetime.time(datetime.now())
instead if you are trying to get the current time or datetime.time(your_date_time)
Where your_date_time = datetime.datetime object
- [Django]-How to find out the request.session sessionid and use it as a variable in Django?
- [Django]-Why do we need to use rabbitmq
- [Django]-Convert an IP string to a number and vice versa
1👍
Have you seen this? https://docs.djangoproject.com/en/dev/ref/models/fields/#default
That’s probably what you’re looking for.
It’s also discussed here: Default value for field in Django model
- [Django]-Django REST Framework combining routers from different apps
- [Django]-QuerySet, Object has no attribute id – Django
- [Django]-Model form save. Get the saved object
0👍
import datetime
default_time = datetime.datetime.now().time()
time_of_visit = models.TimeField(default=default_time)
it will be work fine
- [Django]-Django url pattern – string parameter
- [Django]-Django 1.8: Create initial migrations for existing schema
- [Django]-How to use Python type hints with Django QuerySet?
-2👍
Something like this?
import datetime
dt = datetime.now()
dt.hour = 22
dt.minute = 0
dt.second = 0
Hard to be more specific without context.
- [Django]-How to disable admin-style browsable interface of django-rest-framework?
- [Django]-Getting model ContentType in migration – Django 1.7
- [Django]-Django equivalent of SQL not in