Answer the question
In order to leave comments, you need to log in
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',)
{% 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 %}
Answer the question
In order to leave comments, you need to log in
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('Вы ошиблись при вводе паролей, они не совпадают, введите повторно!')
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',)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question