nima
nima

Reputation: 101

How to send time to model usinig django-admin commands?

I was wondering how can i send a time to django DateTimeField by a django-admin command class , and by time i mean the actual hour and minute not the date. thanks

my django admin command class

class Command(BaseCommand):

def handle(self, *args, **kwargs):
    title = 'new new post'
    try:
        MyModel.objects.create(
            title=title,
            mytime= '???',
        )
        print('%s added' % (title,))
    except:
        print('error')

my model

class MyModel(models.Model):
title = models.CharField(max_length=250)
mytime = models.DateTimeField(null=True, blank=True)

def __str__(self):
    return self.title

Upvotes: 0

Views: 112

Answers (2)

nima
nima

Reputation: 101

solved it using separate DateField and TimeField , thanks

Upvotes: 1

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

Since you're using DateTimeField, you can't save only time, but you can extract the time from it later (record.mytime.time()).

You're looking for function datetime.now:

from datetime import datetime
MyModel.objects.create(
        title=title,
        mytime=datetime.now(),
    )

However Django provides more convenient way how to do this - DateTimeField has a flag auto_now, which sets the time automatically during saving (or auto_now_add if you want to set it only once when the model is created)

class MyModel(models.Model):
    mytime = models.DateTimeField(null=True, blank=True, auto_now=True)

Upvotes: 1

Related Questions