Дата по умолчанию не устанавливает издевательскую дату при сохранении экземпляра

Существует проблема с подражанием методу date.today() при создании экземпляра модели Question через ModelForm. Дата по умолчанию, которая хранится в экземпляре, равна date(2022, 2, 20), тогда как должна быть date(2021, 12, 9). Путь импорта объекта для исправления - "posts.models.date" и models.py фактически имеет оператор импорта from datetime import date.

Что нужно изменить, чтобы дата подражалась правильно, когда экземпляр имеет дату, определенную в тесткейсе?

posts.test.test_forms.py

from datetime import date
from unittest.mock import Mock, patch


class TestDuplicateQuestionPosted(TestCase):
    '''Verify that a User cannot post two questions
    with the exact same title in the same day.'''

    @classmethod
    def setUpTestData(cls):
        user = get_user_model().objects.create_user("TestUser")
        cls.profile = Profile.objects.create(user=user)
        cls.question = Question.objects.create(
            title="Question Title 001", date=date(2021, 12, 9),
            body="This is the extra content about my post: Question__0001",
            profile=cls.profile
        )
        print(Question.objects.all())

    def test_duplicate_question_posted_on_same_day(self):
        with patch("posts.models.date") as mock_date:
            mock_date.today = date(2021, 12, 9)
            data = {
                'title': "Question Title 001",
                "body": "This is the extra content about my post: Question__0001",
                "profile": self.profile
            }
            form = QuestionForm(data)
            self.assertFalse(form.is_valid())
            self.assertTrue(form.has_error("title"))
            self.assertEqual(
                form.errors.as_data()['title'][0].message,
                "Cannot post duplicate question"
            )

posts.models.py

from datetime import date

class Post(Model):

    date = DateField(default=date.today)
    comment = ForeignKey('Comment', on_delete=CASCADE, null=True)
    profile = ForeignKey(
        'authors.Profile', on_delete=SET_NULL, null=True,
        related_name='%(class)ss',
        related_query_name="%(class)s"
    )
    vote = GenericRelation(
        'Vote', related_query_name="%(class)s"
    )
    score = IntegerField(default=0)


    class Meta:
        abstract = True


class Question(Post):

    title = CharField(
        max_length=55, unique_for_date="date",
        help_text="Concisely state the problem you're having",
        error_messages={
            "max_length": "The title of your question is too long"
        }
    )


    class Meta(Post.Meta):
        db_table = "question"
        ordering = ["-score" , "-date"]

    def clean(self):
        super().clean()
        try:
            question_posted = self.__class__.objects.get(
                title=self.title, date=self.date, profile=self.profile
            )
        except self.__class__.DoesNotExist:
            pass
        else:
            raise ValidationError({"title": "Cannot post duplicate question"})

enter image description here

Вернуться на верх