Django: Set datetime.now() in a Form

A tricky little devil this one. For instance, you've got a "created" date in your form and you need it to be set to the current date whenever the page is displayed.

So immediately you go and do this

class SomeForm(forms.Form):
test_datetime = forms.SplitDateTimeField(initial = datetime.datetime.now())

First load, sweet it works. But load the page again, and you'll realise the date is still the same! FUUUUUUUUU!

1283775594667

It seems that the initial date/time is resolved when the server is first initiated. So, how do we fix that?

Easy!

class SomeForm(forms.Form):
test_datetime = forms.SplitDateTimeField(initial = datetime.datetime.now)

Can you spot the difference?

uhERp

Just remove the () from now(). That's it! If we pass it a function, it'll evaluate it on display.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog