i am novice at django development. i am creating a class A which might have multiple class B assigned to it:
class A(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
self.name
class B(models.Model):
a = models.ForeignKey(A)
name = models.CharField(max_length=200)
mydate = models.DateTimeField('party date')
When i am trying to create a new "A" element at the admin page, and creating a matching element B for it and then save()
, i am getting the Warning:
Field 'mydate' doesn't have a default value
If i move the "mydate",element to class A, then when hitting save()
i am getting a message This field is require from Django, requires me to fill the field!
how can i make this required message appear also when date field is part of B!!!
Thanks
If you have not specified, that your field is optional, you will have to provide a value for it every time you create an object. In your case you can't so you will have to do one of those things:
Here is how to make field optional:
class B(models.Model):
a = models.ForeignKey(A)
name = models.CharField(max_length=200)
mydate = models.DateTimeField('party date', blank=True, null=True)
Here is how you set the default value:
import datetime
class B(models.Model):
a = models.ForeignKey(A)
name = models.CharField(max_length=200)
mydate = models.DateTimeField('party date', default=datetime.datetime.now)
There's an utility function in Django
from django.utils import timezone
class B(models.Model):
a = models.ForeignKey(A)
name = models.CharField(max_length=200)
mydate = models.DateTimeField('party date', default=timezone.now)
This function will return you a datetime object based on USE_TZ in settings.py
def now():
"""
Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if settings.USE_TZ:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
else:
return datetime.now()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With