Reputation: 2423
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.
Upvotes: 4
Views: 1797
Reputation: 308799
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:
from django.utils.translation import ugettext_lazy, ugettext as _
class MyForm(forms.Form):
subject = Forms.CharField(initial=_("Title"), max_length=128))
You can then write some javascript to handle the onfocus
event. Here's an untested snippet, using the jQuery .focus()
method.
<script type="text/javascript">
$(function() {
$('#id_subject').focus(function() {
if (this.value == '{{ form.subject.initial }}') {
this.value = '';
}
});
});
</script>
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.
Upvotes: 3
Reputation: 3033
You can provide form.subject.value to the value element of the input.
<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="{% if form.subject.value %}{{ form.subject.value }}{% else %}{% trans "Title" %}{% endif %}"
maxlength="128" />
</div>
Upvotes: 4