M
M
Maxim Zubenko2018-09-23 14:13:29
Django
Maxim Zubenko, 2018-09-23 14:13:29

Django: How to paint field on error in django-bootstrap3 (django-bootstrap4) module?

I made a registration form (in forms.py) and there is also a clean method for validation:

class RegistrationForm(forms.ModelForm):
    password_check = forms.CharField(widget=forms.PasswordInput, label='Повтор пароля')
    password = forms.CharField(widget=forms.PasswordInput, label='Пароль')
    class Meta:
        model = User
        fields = ['username', 'password', 'password_check', 'first_name', 'last_name', 'email']
        labels = {
            'username': 'Логин',
            'first_name': 'Ваше имя',
            'last_name': 'Ваша фамилия',
            'email': 'Email',
        }
        help_texts = {
            'password': 'придумайте пароль не совсем простой',
            'email': 'указывайте реальный адрес, т.к. на него придёт подтверждение'
        }

    def clean(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('Пользователь с данным логином уже зарегистрирован в системе!', code='user exists',)

Made a registration template (registration.html):
{% extends 'base.html' %}
{% load bootstrap3 %}

{% block content %}
    <h3 class="text-center">Регистрация нового пользователя</h3>
    <hr>
<div class="col-xs-offset-3 col-xs-6">
<form method='POST' action='#' class="form-horizontal"> {% csrf_token %}
    {% bootstrap_form form show_label=True layout='horizontal' %}
    {% bootstrap_button "Зарегистрировать" icon="ok" button_type="submit" button_class="btn-success" extra_classes="pull-right" %}
</form>
</div>
{% endblock %}

When an error occurs, a red message pops up, but the field (where the error was found) is not colored, but on the contrary, all fields are colored green. How (forcibly, add something to the clean method or somewhere else) to make the field be painted in the color I need (in fact, you need to add a class, but how?), otherwise this is the picture:
5ba774dc991ab961432770.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Zubenko, 2018-09-23
@JawsIk

In general, I found an interesting method. I will not say that the solution is optimal, but it fulfills its task, although it is some "crutches" (in my opinion).
I called this method "Method of provoking an error, well, or assigning an error" :-). At the same time (as it seems to me) this method will work in all extensions, including the pure version of Django.
The point is. As if we say "but there is an error on this field." And bam everything works. By the way, the error output through raise can generally be disabled in this case, or you can leave it at will. In code, it all looks very simple. Like this:

def clean(self):
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']
        password_check = self.cleaned_data['password_check']

        if User.objects.filter(username=username).exists():
            from django.forms.utils import ErrorList
            self._errors['username'] = ErrorList()
            self._errors['username'].append('Пожалуйста выберите другое имя пользователя, т.к. пользователь с таким логином уже зарегистрирован в системе!')
            # raise forms.ValidationError('Пользователь с данным логином уже зарегистрирован в системе!', code='user exists',)

        if password != password_check:
            from django.forms.utils import ErrorList
            self._errors['password'] = ErrorList()
            self._errors['password'].append(' ')
            self._errors['password_check'] = ErrorList()
            self._errors['password_check'].append('Вы ошиблись при вводе паролей, они не совпадают, введите повторно!')

And so you can make up your own rules. Yes, by the way, the standard rules also work.
ps By the way, the field will not be highlighted if nothing is written in append. That's why I put a space there.
ps2
and here's how to say "they don't take money for demand." I asked the developer of the django-bootstrap3 add-on on github through Google translator. And what was my joy that they answered quickly and accurately. The only thing that is impossible in it (well, or I haven’t found it yet) is to immediately use the POP-up message with the red form. But this is already quite for the sophisticated. And the solution is:
def clean(self):
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']
        password_check = self.cleaned_data['password_check']

        if User.objects.filter(username=username).exists():
            raise forms.ValidationError({'username':'Пожалуйста выберите другое имя пользователя, т.к. пользователь с таким логином уже зарегистрирован в системе!'}, code='user exists')

        if password != password_check:
            raise forms.ValidationError({'password': '',
                                         'password_check': 'Вы ошиблись при вводе паролей, они не совпадают, введите повторно!'}, code='passwords do not match',)

By the way, I don’t know why to insert code at all, but for some reason they require it in the documentation, so I inserted it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question