Перехват ошибок при проверке пароля в Django

У меня проблема. Я пытаюсь отловить ошибки от валидации пароля в Django, но не знаю, как это сделать. Валидация пароля вызывается в forms.py, а form.isValid() вызывается в views.py. Я хотел бы знать, какие именно ошибки были найдены в проверке пароля, вызываемой в forms.py, чтобы я мог использовать if для запуска выбранного мною предупреждения bootstrap. Вот код:

forms.py

class RegistrationForm(forms.Form):
username = forms.CharField(label="Inserisci username", max_length=50)
password = forms.CharField(label="Inserisci password", widget=forms.PasswordInput)
repeatPassword = forms.CharField(label="Ripeti password", widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('Nome utente già in uso')
        return username
    
    def clean_password(self):
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']
        validate_password(password, username)
        return password
    
    def clean_password2(self):
        password = self.cleaned_data['password']
        repeatPassword = self.cleaned_data['repeatPassword']
        if password != repeatPassword:
            raise forms.ValidationError('Le password devono corrispondere')
        return password

views.py

def registration(request):
    if request.method == "POST":
        registrationForm = RegistrationForm(request.POST)
        if registrationForm.is_valid():
            # Creazione utente
            username = RegistrationForm.cleaned_data['username']
            password = RegistrationForm.cleaned_data['password']
            playerStatistics = Statistics(health=randint(90, 110), armor=0, strength=randint(5, 15),
                                          speed=randint(15, 25), dexterity=randint(15, 25))
            equipmentStatistics = Statistics(health=0, armor=0, strength=0, speed=0, dexterity=0)
            playerStatistics.save()
            equipmentStatistics.save()
            equipment = Equipment(statistics=equipmentStatistics)
            equipment.save()
            inventory = Inventory()
            inventory.save()
            newPlayer = Player(username=username, password=password, statistics=playerStatistics,
                               equipment=equipment, inventory=inventory)
            newPlayer.save()
            return render(request, "playerHome.html")
        else:
            return HttpResponse("Errore nell'inserimento dei dati")
    else:
        registrationForm = RegistrationForm()
    return render(request, "registration.html", {"form": registrationForm})

форма регистрации.html

        <form action="/registration/" method="post">
          {% csrf_token %} {{ form|crispy }}
            {% if samePasswordAlert %}
            <div class="alert alert-danger" role="alert">Le password non corrispondono</div>
            {% endif %}
            {% if existingUserAlert %}
            <div class="alert alert-danger" role="alert">Il nome utente è già in uso</div>
            {% endif %}
            {% if tooShortPassword %}
            <div class="alert alert-danger" role="alert">La password deve contenere almeno 8 caratteri</div>
            {% endif %}
            {% if tooSimilarToUserPassword %}
            <div class="alert alert-danger" role="alert">La password è troppo simile al nome utente</div>
            {% endif %}
            {% if tooCommonPassword %}
            <div class="alert alert-danger" role="alert">La password è troppo comune</div>
            {% endif %}
            {% if entirelyNumericPassword %}
            <div class="alert alert-danger" role="alert">La password non può contenere solo numeri</div>
            {% endif %}
          <button type="submit" class="btn btn-primary">Registrati</button>
        </form>

Спасибо

Я пытался использовать form.errors, но я не понимаю, как именно его использовать, поэтому он выдает мне ошибку.

Вернуться на верх