donkeyboy72
donkeyboy72

Reputation: 1943

Django fail to raise an error when a minimum length password is required

I have an form that allows a user to create a user account. I also enforce a minimum password length of 8 and when that is breached , An error would be raise . The problem is , it doesn't raise an error whenever the minimum password length of 8 is breached .

Can someone kindly help me.

def Registration(request):  
    form = UserRegistration()
    if request.method =='POST':
        form = UserRegistration(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'], 
                email=form.cleaned_data['email'], 
                password=form.cleaned_data['password']
                )
            user.is_active = True
            user.save()
             return render(request,'choose.html',{'form':form})

    return render(request, 'register.html', {'form': form},)

my forms.py

 class UserRegistration(forms.Form):
    username = forms.CharField()
    email = forms.EmailField(error_messages={'required':'Error Missing Field , Please Fill this Field'})

    password = forms.CharField(
    widget=forms.PasswordInput(render_value=False)
    )

    MIN_LENGTH = 8

    def clean_password(self):
            password = self.cleaned_data['password']

            if len(password) > self.MIN_LENGTH:
                    raise forms.ValidationError("The new password must be at least %d characters long." % self.MIN_LENGTH)

            return password

My template

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


<span id="error">{{form.username.errors}}</span>
<span id="error2">{{form.email.errors}}</span>
<span id="error3">{{form.password.errors}}</span>

{{form.username}}
{{form.email}}
{{form.password}}
    <input type = "submit" value= "save" id="box2"/>
</form>

Upvotes: 0

Views: 983

Answers (2)

Rohan
Rohan

Reputation: 53376

Your if condition is not correct:

Instead of

if len(password) > self.MIN_LENGTH:

use

if len(password) <= self.MIN_LENGTH:
                #<---- changed condition

Upvotes: 1

Hedde van der Heide
Hedde van der Heide

Reputation: 22459

clean_new_password1 will never be called as new_password1 is not a model field, change it to clean_password, or call super to override any default checking

Upvotes: 3

Related Questions