I created a ModelForm in this way.
class Mant(forms.Modelform):
start_date=forms.CharField()
stop_date=forms.CharField()
def clean_start_date(self):
tz=self.request.session.get('timezone','UTC')
data=self.cleaned_data['start_date']
try:
date_parsed=arrow.get(data,'YYYY-MM-DD HH:mm').replace(tzinfo=tz)
except ParserError as e:
raise forms.ValidationError("invalid format")
return date_parsed.format('YYYY-MM-DD HH:mm:ssZZ')
def clean_stop_date(self):
tz=self.request.session.get('timezone','UTC')
data=self.cleaned_data['stop_date']
try:
date_parsed=arrow.get(data,'YYYY-MM-DD HH:mm').replace(tzinfo=tz)
except ParserError as e:
raise forms.ValidationError("invalid format")
return date_parsed.format('YYYY-MM-DD HH:mm:ssZZ')
The form works nice. validate current dates and all. but my problem is that when there is some problems parsing the date (or any other thing that i add that raise an error) the field comes empty and the user need to select the date all over again.
Every time I see a validation error normal in django the field filled by the user comes back so the user can correct it. but in my case when clean_field is replaced the value filled by the user disappears. there is a way to Fix this?.
Also looks like if the firs element Raise an exception the validation is stopped altogether and all the others errors aren't returned and theirs fields emptied :(
Sorry for answering my own question.
My problem was at template level.
my template was waging for a diatomite object because need to localize the date in the timezone of the user. but when there was an error in the form. the value did not contain a datetime object. just a buffer with the previous input. so the timezone date tags failed to parse the data. printing an empty value.
now the part in the form looks like this.
<input class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm" id="id_start_date" name="start_date" type="text"
{%if form.errors %}
value="{{field.value}}"
{%else%}
value="{{field.value|timezone:user_timezone|date:"Y-m-d H:i"}}"
{% endif %}
when the form came with a errors array Im aware of this and just print the value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.