Search code examples
pythondjangovalidationdjango-formsvalidationerror

How to render ValidationError in Django Template?


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 class="text-center log-in-bg rounded">
    <img class="mb-4" src="{% static "users/images/logo_sign_in.png" %}" alt="" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal text-dark">РЕГИСТРАЦИЯ</h1>
    <form method="post" class="form-signin">
        {% csrf_token %}
        {{ form.email.label_tag }}
        {{ form.email }}
        {{ form.password }}
        {{ form.confirm_password }}
        {{ form.errors }}

        <button class="btn btn-lg btn-sign-in btn-block">Зарегистрироваться</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 =)


Solution

  • 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.