Wednesday, October 7, 2015

Re: KeyError

"is_valid" is a method, you should call

if user_form.is_valid():
    ...

On Wed, Oct 7, 2015 at 2:14 PM, Benjamin Smith <benjaminsmith5050@gmail.com> wrote:
I am making a registration form to register new users using the User model.

This is the forms.py:

class UserForm(forms.ModelForm):
    confirm_email = forms.EmailField(label="Confirm email")

    def clean(self):
        email = self.cleaned_data['email']
        confirm_email = self.cleaned_data['confirm_email']
        password = self.cleaned_data['password']

        if email != confirm_email:
            raise ValidationError({'confirm_email': "Both email doesn't match."})

        if len(password) < 8:
            raise ValidationError({'password': "Password should be of minimum 8 characters."})

        return super(UserForm, self).clean()

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'confirm_email', 'password']

Template:

 {% block content %}
    <p>Register</p>
    <form action="/account/register/" method="POST">
        {% csrf_token %}
        {{ user_form.as_p }}
        <input type="submit" value="Register">
    </form>
{% endblock %}

 views.py:

def register_view(request):
    if request.method == "POST":
        user_form = UserForm(request.POST)
        if user_form.is_valid:
            user = user_form.save()
            return  HttpResponseRedirect('/account/registered/')
    else:
        user_form = UserForm()
    return render(request, 'register_view.html', {
        'user_form': user_form
    })

But I am getting this error while registering a new user when I submit the form:

KeyError at /account/register/

'confirm_email'

How can I solve this problem? Your help will be much appreciated.

Thank you. 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ca83b90f-334d-40cf-8561-fc02462ab80f%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALn3ei3RG%2BLB4qsD%2BEmFO7Os-J-Q_VPvab3J9XapF%2BNcDi9aLQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment