I have a model called Users and I have a form for that model called UsersForm. In my views.py, I created a version of UsersForm, like so
form = UsersForm()
if reqest.method == POST:
form = UsersForm(request.POST)
if form.is_valid():
form.save()
c = {}
c.update(csrf(request))
c.update({'form':form})
return render_to_response('home_page.html', c)
Now, my home_page.html is this:
<html>
<body>
<form method="post" action="">{% csrf_token %}
{{ form }}
<input type="submit" value="Register"/>
</form>
{% if form.errors %}
{% for field in form %}
<p> {{field.errors}} </p>
{% endfor %}
{% endif %}
</body>
</html>
So, what I want is, I want to display only the first error in {{ field.errors}}. What I was thinking was something like:
{% if form.errors %}
{% for field in form %}
<p> {{field.errors}} </p> {{ break}}
{% endfor %}
{% endif %}
but there is no break in the django template language, right? I also tried thinking about using {% for field in form|slice:":1" %} but that wouldn't work either. Anyone know how to do this?
You can index lists in a django template by using the dot notation:
{{ field.errors.0 }}
Be sure to check that there is at least 1 error before doing that though, or you will get an Index out of range error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With