我正在使用Django 2.0
我有一个模型课
class AmountGiven(models.Model):
amount = models.FloatField(help_text='Amount given to the contact')
_given_date = models.DateTimeField(
db_column='given_date',
default=datetime.now,
help_text='Date and time when amount was given to the contact'
)
return_date = models.DateTimeField(
blank=True,
default=None,
null=True
)
modified = models.DateTimeField(auto_now_add=True)
created = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.amount)
@property
def given_date(self):
return self._given_date
@given_date.setter
def given_date(self, value):
value_2 = value
try:
value_2 = datetime.strptime(value_2, "%Y-%m-%d %H:%M:%S").date()
except ValueError:
try:
datetime.combine(value, datetime.min.time())
value_2 = datetime.strptime(value_2, "%Y-%m-%d").date()
except ValueError:
raise ValueError("Date is not of valid format. %Y-%m-%d %H:%M:%s")
if value_2 > datetime.today().date():
raise ValueError("The date chosen was in the future.")
self._given_date = value
我想验证是否给定的日期不是将来的日期。如果将来given_date
,它将引发验证错误,并且不会保存表单数据。
在pytest
中,我正在做
@pytest.mark.django_db
class TestAmountGiven(TestCase):
def test_model_add_amount_given(self):
amount_given = AmountGiven(
amount=10000.00,
given_date='2018-1-30 00:00:00',
promised_return_date='2019-02-01 00:00:00'
)
amount_given.save()
但这是警告
transactions/tests/test_models.py::TestAmountGiven::test_model_add_amount_given
/path_to/python3.6/site-packages/django/db/models/fields/__init__.py:1423:
RuntimeWarning: DateTimeField AmountGiven._given_date received a naive datetime (2018-01-30 00:00:00) while time zone support is active.
RuntimeWarning)
/path_to/python3.6/site-packages/django/db/models/fields/__init__.py:1423:
RuntimeWarning: DateTimeField AmountGiven.promised_return_date received a naive datetime (2019-02-01 00:00:00) while time zone support is active.
RuntimeWarning)
1。这是编写现场验证的正确方法吗? (使用二传手)
2.如何解决警告消息