I am working on multilanguage form which is translated by i18n and I’ve occurred a problem.
When I use {{ form.as_p }} for generating forms and I provide invalid data to the form, the data provided earlier is not being cleaned from the form – and I want same behavior in my custom form which will have some fields translated.
This is my custom form:
<div class="">
{{ form.subject.errors }}
<input class="contact_form" id="id_subject"
type="text" name="subject"
onfocus="if(this.value=='{% trans "Title" %}') this.value=''"
value="{% trans "Title" %}"
maxlength="128" />
</div>
How I can modify its behavior so it wont clean the provided data after an error? And only fields which contained invalid dada sould get removed from the form.
I couldn’t find anything in the django docs for that issue.
Sander’s answer is correct, but if possible, you should try to avoid manually rendering your form fields in the template. In this case, you can set a initial value when you define the form:
You can then write some javascript to handle the
onfocusevent. Here’s an untested snippet, using the jQuery.focus()method.You could also try passing the onfocus as a widget attribute. As you are using translatable strings, this might be a bit complicated – I think you might have to set the widget in the form’s
__init__method.