Z
Z
zigen2015-12-04 14:51:12
Django
zigen, 2015-12-04 14:51:12

How to get form.errors error text in view?

Good afternoon.
There was a task to drag an authorization form on each page of the site.
Made through the inclusion tag.

<form  method="post" action="{% url 'login' %}">
      {% csrf_token %}
      <tr>
          <td>
              <label class=""  for="name"></label>
              {{ auth_form.username }}
          </td>
          <td>
              <label class=""  for="pwd"></label>
              {{ auth_form.password }}
              <input type="submit" class="header__form_button" value="ОК">
          </td>
      </tr>
  </form>

But I don’t know how to return an error, of course, you can’t throw the form into any view.
It came to mind to use messages.
if request.method == 'POST':
        form = AuthUserFormPanel(data=request.POST)
        if form.is_valid():
            login(request, form.get_user())
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'), '/')
        messages.add_message(request, messages.ERROR, form.errors)
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'), '/')

However, form.errors returns:
<ul class="errorlist"><li>__all__<ul class="errorlist nonfield"><li>Пожалуйста, введите правильные имя пользователя и пароль. Оба поля могут быть чувствительны к регистру.</li></ul></li></ul>

I only need text
Please enter the correct username and password. Both fields can be case sensitive.

Do not parse this output?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2015-12-04
@zigen

Of course, you can’t throw the form into any view.
you can do this
https://docs.djangoproject.com/en/1.8/topics/auth/...
You make a function into which you pass request and return a dictionary of values ​​from it, depending on whether the user is logged in or not
You can make a mixin for CBV

V
Vladimir, 2015-12-04
@vintello

the question, by the way, is a good one about getting errors. I also once wondered - to parse or not to parse :) it
is solved like this:

for field in form.errors:
               error[field]=form.errors[field].as_text()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question