简体   繁体   中英

Key_error using self.cleaned_data[] in Django forms

I keep getting a key_error on line email = self.cleaned_data["email"] of the below in my forms.py. I am trying to also add an email validation or clean_email method, because somehow it seems that the key_error only occurs when I try registering with an invalid email address . Is adding def clean_email() the right approach? And if so, is the forms.py inside my class the right place to do so?

forms.py:

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


class RegisterForm(forms.Form):
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "First Name", 'autocomplete': "nope"}), label="First name", max_length=64, required=True)
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Last Name", 'autocomplete': "new-password"}), label="Last name", max_length=64, required=True)
    email = forms.EmailField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Email", 'autocomplete': "new-password"}), label="Email", max_length=132, required=True)
    password = forms.CharField(label="Password", max_length=32, widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Password"}))
    confirmation = forms.CharField(label="Confirmation", max_length=32, widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Confirm"}))

    def clean(self):
        email = self.cleaned_data["email"]
        if User.objects.filter(username=email).exists():
          raise forms.ValidationError(u'Email "%s" is already in use.' % email)

        password = self.cleaned_data["password"]
        confirmation = self.cleaned_data["confirmation"]
        if password != confirmation:
            raise forms.ValidationError("Password and confirmation do not match!")

The correspoinding method in views.py is:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.contrib import messages

def register_client(request):
  if request.method == "POST":
    form = RegisterForm(request.POST)

    if form.is_valid():
      email = form.cleaned_data['email']
      password = form.cleaned_data['password']
      user = User.objects.create_user(email, email, password)
      user.first_name = form.cleaned_data['first_name']
      user.last_name = form.cleaned_data['last_name']
      user.save()

  else:
    form = RegisterForm()

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

register.html:

{% extends "pizza/outerlayout.html" %}

{% block title %}
Register for Pizza
{% endblock %}

{% block body %}

<form action="{% url 'register_client' %}" class="form-signin" method="post" autocomplete="false">
  {% csrf_token %}
  {% load static %}
  <img class="mb-4" src="{% static 'pizza/pizza.jpg' %}" alt="" width="72" height="72">
  <h1 class="h3 mb-3 font-weight-normal">Register as Pizza Client</h1>
  {{ form }}

  <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>

</form>

{% endblock %}

Traceback:

Internal Server Error: /register_client
Traceback (most recent call last):
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/mnt/c/git/project3/orders/views.py", line 43, in register_client
    if form.is_valid():
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/forms/forms.py", line 179, in is_valid
    return self.is_bound and not self.errors
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/forms/forms.py", line 174, in errors
    self.full_clean()
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/forms/forms.py", line 377, in full_clean
    self._clean_form()
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/forms/forms.py", line 404, in _clean_form
    cleaned_data = self.clean()
  File "/mnt/c/git/project3/orders/forms.py", line 14, in clean
    email = self.cleaned_data["email"]
KeyError: 'email'

Thanks vm and apologies for basic question - am a newbie to this.

try this:

def clean_email(self):   #add clean_email
    email = self.cleaned_data["email"]
    if User.objects.filter(username=email).exists():
      raise forms.ValidationError(u'Email "%s" is already in use.' % email)

make a another def clean_password() for password validation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM