Django 'DateTimeField' has no default

I am new to django development. I create a class A to which several classes B can be assigned:

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 try to create a new element "A" on the admin page and create the corresponding element B for it, and then save() , I get a warning: The 'mydate' field has no default value

If I moved the "mydate" element to class A, then when I click save() I get the message This field is required from Django, I need to fill in the field!

how can I make this mandatory message also appear when the date field is part B !!!

thanks

+6
source share
3 answers

If you have not indicated yet that your field is optional, you will need to indicate its value each time you create an object. In your case, you cannot do this, you will have to do one of these things:

Here's how to make the 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) 

This 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) 
+12
source

There is a 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 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() 
+4
source

From my point of view, django will try to test model A and then return validation errors. As A checks, he tries to write A, which does not work, since B does not check. I’m not sure whether to do this elegantly, but if you try to evaluate Form B yourself, before checking A you will receive a message “this field is required”, which you can display to the user.

0
source

Source: https://habr.com/ru/post/887685/


All Articles