最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Remove the mandatory field label 'This field is required.' and fix the bug with 'clean_email&am

programmeradmin5浏览0评论

I use the built-in Django, 'UserCreationForm' to create a registration form, but there are unnecessary instructions 'This field is required.' that these fields are required, I want to remove them, please help, or at least translate into Russian, so that the inscription is in Russian, if you can, also help fix clean_email in forms, so that it does not always throw out this inscription after 1 test entry of an existing email here is a screenshot of the result RegisterUserForm

views.py:

class RegisterUser(CreateView):
    form_class = RegisterUserForm
    template_name = 'users/register.html'
    extra_context = {'title': 'Регистрация'}
    get_success_url = reverse_lazy('users:login')

forms.py:

class RegisterUserForm(UserCreationForm):
    username = forms.CharField(label="Логин:", widget=forms.TextInput(attrs={'class': "form-input"}))
    password1 = forms.CharField(label="Пароль:", widget=forms.PasswordInput(attrs={'class': "form-input"}))
    password2 = forms.CharField(label="Повтор пароля:", widget=forms.PasswordInput(attrs={'class': "form-input"}))

    class Meta:
        model = get_user_model()
        fields = {'username', 'email', 'first_name', 'last_name', 'password1', 'password2'}
        labels = {
            'username': 'Логин:',
            'email': 'E-mail:',
            'first_name': 'Имя:',
            'last_name': 'Фамилия:',
            'password1': 'Пароль:',
            'password2': 'Повторить пароль:',
        }
        widgets = {
            'username': forms.TextInput(attrs={'class': "form-input"}),
            'first_name': forms.TextInput(attrs={'class': "form-input"}),
            'last_name': forms.TextInput(attrs={'class': "form-input"}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.order_fields(['username', 'email', 'first_name', 'last_name', 'password1', 'password2'])

    def clean_email(self):
        email = self.cleaned_data['email']
        if get_user_model().objects.filter(email=email).exists():
            raise forms.ValidationError(("E-mail должен быть уникальным!"), code="invalid")
        return email

users/register.html:

{% extends 'users/base.html' %}

{% block title %}Регистрация{% endblock %}

{% block content %}
<h1>Регистрация</h1>
<form method="post">
    {% csrf_token %}
    {% for f in form %}
    <p><label class="form-label" for="{{ f.id_for_label }}">{{ f.label }} </label>{{ f }}</p>
    <div class="form-error">{{ f.errors }}</div>
    {% endfor %}
    <p><button type="submit">Регистистрация</button></p>
</form>
{% endblock %}

I've used the AI ​​and watched videos, but apparently no one has had this question in their head all this time. I'm sure it's very easy to do, but I don't know how.

I use the built-in Django, 'UserCreationForm' to create a registration form, but there are unnecessary instructions 'This field is required.' that these fields are required, I want to remove them, please help, or at least translate into Russian, so that the inscription is in Russian, if you can, also help fix clean_email in forms, so that it does not always throw out this inscription after 1 test entry of an existing email here is a screenshot of the result RegisterUserForm

views.py:

class RegisterUser(CreateView):
    form_class = RegisterUserForm
    template_name = 'users/register.html'
    extra_context = {'title': 'Регистрация'}
    get_success_url = reverse_lazy('users:login')

forms.py:

class RegisterUserForm(UserCreationForm):
    username = forms.CharField(label="Логин:", widget=forms.TextInput(attrs={'class': "form-input"}))
    password1 = forms.CharField(label="Пароль:", widget=forms.PasswordInput(attrs={'class': "form-input"}))
    password2 = forms.CharField(label="Повтор пароля:", widget=forms.PasswordInput(attrs={'class': "form-input"}))

    class Meta:
        model = get_user_model()
        fields = {'username', 'email', 'first_name', 'last_name', 'password1', 'password2'}
        labels = {
            'username': 'Логин:',
            'email': 'E-mail:',
            'first_name': 'Имя:',
            'last_name': 'Фамилия:',
            'password1': 'Пароль:',
            'password2': 'Повторить пароль:',
        }
        widgets = {
            'username': forms.TextInput(attrs={'class': "form-input"}),
            'first_name': forms.TextInput(attrs={'class': "form-input"}),
            'last_name': forms.TextInput(attrs={'class': "form-input"}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.order_fields(['username', 'email', 'first_name', 'last_name', 'password1', 'password2'])

    def clean_email(self):
        email = self.cleaned_data['email']
        if get_user_model().objects.filter(email=email).exists():
            raise forms.ValidationError(("E-mail должен быть уникальным!"), code="invalid")
        return email

users/register.html:

{% extends 'users/base.html' %}

{% block title %}Регистрация{% endblock %}

{% block content %}
<h1>Регистрация</h1>
<form method="post">
    {% csrf_token %}
    {% for f in form %}
    <p><label class="form-label" for="{{ f.id_for_label }}">{{ f.label }} </label>{{ f }}</p>
    <div class="form-error">{{ f.errors }}</div>
    {% endfor %}
    <p><button type="submit">Регистистрация</button></p>
</form>
{% endblock %}

I've used the AI ​​and watched videos, but apparently no one has had this question in their head all this time. I'm sure it's very easy to do, but I don't know how.

Share Improve this question asked Jan 18 at 0:46 nahidnahid 11 silver badge3 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

You can override the default messages the field raises by passing the error_messages argument. You would have to pass in a dictionary with keys matching the error messages you want to override. Here is an example of a custom error message:

username = forms.CharField(error_messages={"required": "Please enter your name"})

You can verify by calling username.clean("") which will raise the custom error message:

Traceback (most recent call last):
ValidationError: ['Please enter your name']

See the docs

EDIT based on OP's comments: To remove all error messages in form fields, simply remove the field.errors tag from your templates as shown below:

{% for field in form %}
    <div class="fieldWrapper">

        <!-- remove or comment this -->
        <!-- {{ field.errors }} -->

        {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
          <p class="help" id="{{ field.auto_id }}_helptext">
            {{ field.help_text|safe }}
          </p>
        {% endif %}
    </div>
{% endfor %}

See Looping over the form’s fields

register.html:

{% extends 'users/base.html' %}

{% block title %}Регистрация{% endblock %}

{% block content %}
<h1>Регистрация</h1>
<form method="post">
    {% csrf_token %}
    {% for f in form %}
    <div class="form-error">
        {# Отображаем только ошибки, не связанные с обязательностью поля #}
        {% for error in f.errors %}
            {% if error != "Обязательное поле." %}  {# Или другое сообщение по умолчанию #}
                {{ error }}
            {% endif %}
        {% endfor %}
    </div>
    <p><label class="form-label" for="{{ f.id_for_label }}">{{ f.label }} </label>{{ f }}</p>
    {% endfor %}
    <p><button type="submit">Регистрация</button></p>
</form>
{% endblock %}

we simply filter errors in html for required fields and if the condition is met we do not show the error

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论