Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms: Validation message not showing

Can anyone spot what I'm doing wrong in the following example. Validating messages are not appearing in my template when incorrect details are entered such as a invalid email address. The template is loading and there are no errors.

I'm excepting validation messages to be printed on page, however for some reason this has suddenly stop working. As you can see from the code example below I'm passing the form in the context back to the template. this used to work and today just stopped.

view.py

if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # If form has passed all validation checks then continue to save member.
            user = User.objects.create_user(
                                            username=form.cleaned_data['username'],
                                            email=form.cleaned_data['email'], 
                                            password=form.cleaned_data['password']
                                            )
            user.save()
            #member = User.get_profile()
            #member.name = form.cleaned_data['name']
            #member.save()
            member = Member(
                            user=user,
                            name=form.cleaned_data['name']
                            )
            member.save()

            # Save is done redirect member to logged in page.
            return HttpResponseRedirect('/profile')
        else:
            # If form is NOT valid then show the registration page again.
            form = RegistrationForm() 
            context = {'form':form}
            return render_to_response('pageRegistration.html', context,context_instance=RequestContext(request))

form.py

class RegistrationForm(ModelForm):
    username = forms.CharField(label=(u'User Name'))
    email = forms.EmailField(label=(u'Email'))
    password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
    passwordConfirm = forms.CharField(label=(u'Confirm Password'), widget=forms.PasswordInput(render_value=False))

    class Meta:
        model = Member
        # Don't show user drop down.
        exclude = ('user',)


    def clean_username(self):
        username = self.cleaned_data['username']
        try:
                User.objects.get(username=username)
        except User.DoesNotExist:
                return username
        raise forms.ValidationError("Username already taken.")


    def clean(self):
        try:   
            cleaned_data = super(RegistrationForm, self).clean() 
            password = cleaned_data.get("password")
            passwordConfirm = cleaned_data.get('passwordConfirm')

            if password != passwordConfirm:
                raise forms.ValidationError("Password does not match, try again.")
            return cleaned_data
        except:
            raise forms.ValidationError("Error")

pageRegistration.html

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

            {% if forms.errors %}
            <p>
                correct some stuff
            </p>
            {% endif %}

            {{form}}
            <br>
            <input type="submit" value="submit">
        </form>  
like image 841
Prometheus Avatar asked Apr 18 '26 22:04

Prometheus


1 Answers

Since, the form is not validate in the else clause your form variable is overriden with a new form where it looses all of the errors

if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # If form has passed all validation checks then continue to save member.
            user = User.objects.create_user(
                                            username=form.cleaned_data['username'],
                                            email=form.cleaned_data['email'], 
                                            password=form.cleaned_data['password']
                                            )
            user.save()
            #member = User.get_profile()
            #member.name = form.cleaned_data['name']
            #member.save()
            member = Member(
                            user=user,
                            name=form.cleaned_data['name']
                            )
            member.save()

            # Save is done redirect member to logged in page.
            return HttpResponseRedirect('/profile')
        return render_to_response('pageRegistration.html', context,context_instance=RequestContext(request))
like image 105
Raunak Agarwal Avatar answered Apr 21 '26 11:04

Raunak Agarwal