Django - form resets values ​​after error

I am working on a multilingual form that i18n translates and I am having a problem.

When I use {{form.as_p}} to create forms and I provide invalid form data, the data previously provided is not cleared from the form - and I want the same behavior in my custom form, which will have some fields translated.

This is my usual 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 can I change its behavior so that it doesn't clear the supplied data after an error? And only fields containing an invalid dada can be removed from the form.

I couldn't find anything in the django docs for this problem.

+3


source to share


2 answers


Sander's answer is correct, but if possible, you should try to avoid manually rendering form fields in a template. In this case, you can set an initial value when defining the shape:

from django.utils.translation import ugettext_lazy, ugettext as _

class MyForm(forms.Form):
    subject = Forms.CharField(initial=_("Title"), max_length=128))

      

Then you can write some javascript to handle the event onfocus

. Here's an untested snippet using jQuery's method .focus()

.



<script type="text/javascript">
$(function() {
  $('#id_subject').focus(function() {
    if (this.value == '{{ form.subject.initial }}') {
      this.value = '';
    }
  });
});
</script>

      

You can also try passing onfocus as a widget attribute . Since you are using translatable strings this can be a little tricky - I think you might have to set a widget on a form __init__

.

+3


source


You can provide form.subject.value for the input value element.



<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>

      

+3


source







All Articles