takz
takz

Reputation: 23

Django Error handling with two forms with same fields

I have two forms in single template, and I want to display separate error msg independent from each other.

index.html

<form id="signin" action="{% url auth_login %}" method="post" accept-charset="utf-8">
{% csrf_token %}
 <fieldset id="signin_menu">
 <label for="username">Username</label>
 <input id="username" name="username" value="" title="username"type="text">
 </fieldset>
</form>

<form action="/accounts/register/" method="post" accept-charset="utf-8">
{% csrf_token %}
<fieldset id="register_set">
 <label for="username">Username</label>
 <input id="username" name="username" value="" title="username"type="text">
 </fieldset>
</form>

I tried this code:

{% if form.username.errors %}
    {% for error in form.username.errors %}
<span class="error_message">{{ error|escape }}  </span>
{% endfor %}
{% endif %}

Since I am using same username. It displays error msg on both form, if I place the code above.

Upvotes: 0

Views: 239

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34563

Django has no way of knowing which form you're referring to in the DOM when each form has the same fields with the same name. You also have two fields with the same ID, which is invalid HTML. The value of the ID attribute must be unique. I would recommend prefixing your forms to keep the namespaces separate.

Upvotes: 1

Related Questions