Date and time values ​​in Django forms (source and submitted have a different format)

For some reason, I use my own HTML to display the form. My form input gets the initial value (date) and shows the same form after submitting.

But after sending, the input does not have the previously selected value (only empty).

I use {{ Form.Fileld.value|date:"Ymd" }} in temlate to get the initial and represented values.

It seems that the initial and represented values ​​are in different formats: "datetime" for the initial values ​​and "string" after sending.

Here is my simple test:

The form

 class ShowStartEndDateForm(forms.Form): start_date = forms.DateField(initial=date.today().replace(day=1), label="Start", widget=forms.DateInput(format='%Y-%m-%d'), input_formats=['%Y-%m-%d']) ... 

View

 if request.method == 'POST': form_date = ShowStartEndDateForm(request.POST) if form_date.is_valid(): form_was_submitted = True cd = form_date.cleaned_data operator = cd['operators'] days=[] for day in range(0,(cd['end_date']-cd['start_date']).days+1): days.append(cd['start_date']+relativedelta(days=+day)) else: form_date = ShowStartEndDateForm() return render_to_response('epay.html', locals(), context_instance=RequestContext(request)) 

Template

 <!- HTML FORM here |classname is my custom template filter. --> Date1: {{ form_date.start_date.value|date:"Ymd" }} \ ({{ form_date.start_date.value|classname }}) Date2: {{ form_date.start_date.value }} 

The first call in the browser:

 Date1: 2013-10-01 (date) Date2: 1 October 2013 

After the submit form:

 Date1: (unicode) Date2: 2013-10-01 

What am I doing wrong? What is the correct way to access the original and submitted form field values?

You know.

+6
source share
1 answer

You are wondering a bit confusing (you have to add some more of your actual code), but from experience I know that when mixing between formats this is a good agreement to just do it all in one place. Therefore, instead of specifying the format on the client side, like you, specify it all on the form itself, and then everything will (should) be synchronized.

 class ShowStartEndDateForm(forms.Form): start_date = forms.DateField(initial=date.today().replace(day=1), label="Start", widget=DateInput(format='%Y-%m-%d'), input_formats=['%Y-%m-%d']) 

i.e. you specify the DateInput widget which form to take, and you indicate input_formats (for the field itself) which formats to expect (you can add several). Also, if you are using some type of datepicker, you should of course make sure that it also uses the correct format.

Edit

I reproduced this and everything was fine:

 In [1]: from test.forms import * In [2]: f = ShowStartEndDateForm() In [3]: print f <tr> <th><label for="id_start_date">Start:</label></th> <td><input id="id_start_date" name="start_date" type="text" value="2013-10-01" /></td> </tr> 

(of course, I changed the indent here so you can see it more clearly)

+5
source

Source: https://habr.com/ru/post/955590/


All Articles