Home > Blockchain >  How to render ValidationError in Django Template?
How to render ValidationError in Django Template?

Time:07-24

I am new in Django, and I ask community help.

Now I I'm working on user registration and I want to do password validation: if passwords are not repeated, a message appears below the bottom field. As far as I understand, {{ form.errors }} must be used to render the error text specified in ValidationError , but when this error occurs, its text is not displayed on the page. Please tell me how to solve this problem. Perhaps I did not quite understand how Django forms work. I tried the solutions suggested in other answers, but unfortunately nothing worked so far. Thank you.

forms.py:

from .models import CustomUser

class RegisterUserForm(forms.ModelForm):
    email = forms.EmailField(required=True,
                            label="Адрес электронной почты",
                            widget=forms.EmailInput(attrs={'class': 'form-control',
                                                        'placeholder':'email'}))
    password = forms.CharField(label='Пароль',
                            widget=forms.PasswordInput(attrs={'class': 'form-control',
                                                            'placeholder':'password'})                                                            )
    confirm_password = forms.CharField(label='Пароль(повторно)',
                            widget=forms.PasswordInput(attrs={'class': 'form-control',
                                                            'placeholder':'confirm password'}))


    def clean(self):
        super().clean()
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if password != confirm_password:
            raise ValidationError({'confirm_password': 'пароли не совпадают'})


  class Meta:
        model = CustomUser
        fields = ("email", "password", "confirm_password")

views.py:

def sign_up(request):
    if request.method=="POST":
        form = RegisterUserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('pages:index')

    form = RegisterUserForm()
    return render(request=request, template_name="users/sign_up.html", context={'form': form})

template:

</head>
    <link rel="stylesheet" type="text/css" href="{% static 'users/css/style.css' %}">
<head>

<div >
    <img  src="{% static "users/images/logo_sign_in.png" %}" alt="" width="72" height="72">
    <h1 >РЕГИСТРАЦИЯ</h1>
    <form method="post" >
        {% csrf_token %}
        {{ form.email.label_tag }}
        {{ form.email }}
        {{ form.password }}
        {{ form.confirm_password }}
        {{ form.errors }}

        <button >Зарегистрироваться</button>
    </form>
</div>

Thanks for the help. I hope my question is not too primitive - I'm just at the beginning of learning Django, I may not know some things =)

CodePudding user response:

Option 1)

Generally speaking, validation errors in clean() appear in

{{ form.non_field_errors }} 

...because they are not linked to a particular field. In this case, it involves two fields. If you include the above in your template, and modify your error message to...

raise ValidationError('пароли не совпадают')

...then the error should show on your page.

Option 2)

Looking closer, I see you have tried to add it an an error message for the confirm_password field. While that's not the default, if you want to handle it that way you can remove the current raise ValidationError lines and use the following in your clean method to assign the error to a particular field.

self.add_error('confirm_password', 'пароли не совпадают')

CodePudding user response:

Error was in view. This is corrected view:

def sign_up(request):
    if request.method=="POST":
        form = RegisterUserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('pages:index')
    else:        
        form = RegisterUserForm()
    return render(request, template_name="users/sign_up.html", context={'form': form})

I was making new request to form. And context with mistakes was cleaned. else using helped me to save this context. By other side SamSparx answer helped to understand me, how to use add_error.

  • Related