1

I am trying to create user registration in Django but When I enter 2 wrong passwords I can't display a validation error message. Actually, I checked Django documents everything seems good.

I just checked the original source and I couldn't find an error message to override like other fields.

views.py 

from django.shortcuts import render,redirect
from  .forms import RegisterForm

from django.contrib.auth.models import User
from django.contrib.auth import login

# Create your views here.

def register (request):
    if request.method == "post":
        form = RegisterForm(request,POST)
        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")

            newUser = User(username =username)
            newUser.set_password(password)

            newUser.save()
            login(request,newUser)

            return redirect("index")
        context = {
            "form" : form
        }
        return render(request,"register.html",context)


    else:
        form = RegisterForm()
        context = {
            "form" : form
        }
        return render(request,"register.html",context)

forms.py

from django import forms
from django.core.exceptions import ValidationError

class RegisterForm(forms.Form):
    username = forms.CharField(max_length =50,label = "kullanici adi")
    password = forms.CharField(max_length=20, label = 'parola', widget = forms.PasswordInput)
    confirm = forms.CharField(max_length=20, label= "Parolayi dogrula", widget= forms.PasswordInput)


    def clean(self):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        confirm = self.cleaned_data.get("confirm")

        if password and confirm and password != confirm :
            raise forms.ValidationError("parola eslesmiyor")

        values = {
            "username" : username,
            "password" : password
        }

        return values

register.html

<!DOCTYPE html>

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>login</title>

  </head>
  <body>

    <form method="POST">
      {% csrf_token %}

      {{form.as_p}}
      <br>
      <button type="submit" class="btn btn-danger">Kayit ol</button>
    </form>
  </body>
</html>
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
berkay
  • 11
  • 2

3 Answers3

0

In django template: you need to show

{{form.non_field_errors}}

.

Liza Amatya
  • 141
  • 6
0

Try returning cleaned_data itself

def clean(self):
    if password and confirm and password != confirm :
        raise forms.ValidationError("parola eslesmiyor")
    return self.cleaned_data
Liza Amatya
  • 141
  • 6
0

Have you tried looping through the form errors? You can check this answer for a detailed explanation: Django Forms: if not valid, show form with error message

Brandon
  • 46
  • 7