Hidden datetime field in newforms

98 views
Skip to first unread message

juampa

unread,
Feb 19, 2007, 11:25:34 AM2/19/07
to Django users
I have a certain model that contains a datetime field and I am using
newforms to create and edit entries for this model. One of the fields
in the model is a datetime set only for an entry creation. To modify
one of these entries, I create a form from the instance
(form_for_instance()) and set the datetime field to hidden
(widgets.HiddenInput()). The problem is that I get a validation error
upon submitting the modified entry because the HTML from the form
contains tha date as:

<input type="hidden" name="date_posted" value="2007-02-19
09:36:22.531015" id="id_date_posted" />

but the corresponding field on the form does not accept all those
decimal places for the seconds in the time.

Is there an elegant way to fix this or do I just have to manually
clean up the time before I save the modified entry?

Thanks.

Collin Grady

unread,
Feb 19, 2007, 4:55:24 PM2/19/07
to Django users
Define a clean_date_posted to trim the decimals?

juampa

unread,
Feb 19, 2007, 5:30:32 PM2/19/07
to Django users

On Feb 19, 3:55 pm, "Collin Grady" <cgr...@gmail.com> wrote:
> Define a clean_date_posted to trim the decimals?

But the question is where. After you create the form class with

FormClass = forms.models.form_for_instance(anInstance)
. . .
form = FormClass(request.POST)

the form is bound to the data and it can't be changed, and
form.is_valid() will hit a validation error because the POST has the
datetime with all the decimal places.

So, the only place I can think of removing the decimals is after you
retrieve anInstance from the database, and before you used to create
the form class. And it seems a bad idea to have to modify the database
data for this purpose. It seems the problem arises when the form field
uses the strptime() method to parse and validate the input. There is
no way to specify a format string with decimals. My guess is that the
form_for_instance(anInstance) call should trim the decimals
automatically, so that the hidden field has the proper data without
intervention. However, this would also result in indirect database
modification. Perhaps the solution is to override the save() method in
the model and trim the decimals there.

Thanks,


juampa

unread,
Feb 19, 2007, 8:47:27 PM2/19/07
to Django users
Collin:

I did not know enough earlier to understand your answer, but I do now.
Thanks.

Juan Pablo

Reply all
Reply to author
Forward
0 new messages