I use django.utils.timezone.now() in a lot of my code. It returns the datetime in the timezone specified in settings.py. One side effect of using this function is that during testing, you may want “now()” to be a fixed date time. No worries. Mock to the rescue. Here is the code:
from django.test import TestCase
from django.utils import timezone
# Make now() a constant
NOW_FOR_TESTING = datetime.datetime(2015, 10, 10, 10)
# This is the function that replaces django.utils.timezone.now()
# This function shows that the mocking is in effect even outside of the TestMyTest scope.
def test_time_zone(self, *args):
# After patching, mock passes in some extra vars. Put *args to handle them.
Note that you need to add the “*args” argument to the methods in your TestCase class.
Here is how to add to the default DATETIME_INPUT_FORMATS in Django settings.py:
from django.conf.global_settings import DATETIME_INPUT_FORMATS
DATETIME_INPUT_FORMATS += ('%Y-%m-%d %I:%M %p', )
Usually I use datetimes as timestamps that are automatically set. Thus I do not need a datetime widget. But in my current project I needed a datetime widget that was user friendly. There are a few options. Which one was best?
That’s when I rediscovered a module by Trent Richardson (jquery-ui-timepicker-addon). I have used some of his modules in the past and had good luck. I am already using jquery. This module will not interfere with django-crispy. Turns out it worked great!