Django's ModelForm with an HiddenInput returns invalid
--
Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001
--
Chapters
00:00 Question
01:46 Accepted answer (Score 1)
03:10 Answer 2 (Score 2)
03:27 Answer 3 (Score 1)
03:42 Thank you
--
Full question
https://stackoverflow.com/questions/4485...
Accepted answer links:
http://docs.djangoproject.com/en/dev/ref...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #djangoforms
#avk47
ANSWER 1
Score 2
Do you want the pub date to be the date of the post? Is so have you tried auto_now in your models?
pub_date = models.DateTimeField(auto_now=True)
ACCEPTED ANSWER
Score 1
The problem is in the conversion from string to datetime object.
The datetime field, if no input_formats argument is specified, takes these formats for string->datetime conversion.
(from the docs: http://docs.djangoproject.com/en/dev/ref/forms/fields/#datetimefield)
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
So your value of 2010-12-19 17:08:22.498000 won't work.
The default widget for DateTimeField is DateTimeInput widget which formats the datetime to a string correctly, but HiddenInput just takes the datetime object w/ no formatting as you've shown.
If you want to use HiddenInput you need to strftime the datetime object to be in the correct format.
An alternative option if you just want to hide it is to not set the widget as HiddenInput but simply keep the DateTimeInput widget as is and hide that element with the attrs argument.
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('title', 'message', 'pub_date',)
widgets = {
'message' : Textarea(attrs={'cols':80, 'rows':20}),
'pub_date' : DateTimeInput(attrs={'style': 'display:none;'}),
}
ANSWER 3
Score 1
Another alternative is to just change the widget type to SplitHiddenDateTimeWidget