Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: how to access only first error message in form.errors?

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?

like image 410
SilentDev Avatar asked Mar 23 '23 07:03

SilentDev


1 Answers

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.

like image 70
jproffitt Avatar answered Apr 06 '23 01:04

jproffitt