'How can I solve this KeyError
Solution 1:[1]
Good day!
Probably, there is an error in the template HTML with missing user_email field in the <form>.
# form.py
from django import forms
from django.core import validators
class UserForm(forms.Form):
user_email = forms.EmailField()
user_vmail = forms.EmailField()
def clean(self):
all_data = super().clean()
print(all_data)
user_email = all_data["user_email"]
user_vmail = all_data["user_vmail"]
if user_email != user_vmail:
raise forms.ValidationError("Email does not match")
This gives be the following:
[26/Jan/2022 05:57:32] "GET / HTTP/1.1" 200 3702
{'user_email': '[email protected]', 'user_vmail': '[email protected]'}
[26/Jan/2022 05:57:43] "POST / HTTP/1.1" 302 0
[26/Jan/2022 05:57:43] "GET / HTTP/1.1" 200 3702
The source code: https://github.com/almazkun/django_form
Solution 2:[2]
For more information, I strongly recommend checking the documentation, https://docs.djangoproject.com/en/4.0/ref/forms/validation/#form-field-default-cleaning
def clean(self):
cleaned_data = super().clean()
user_email= cleaned_data.get("user_email")
user_vmail = cleaned_data.get("user_vmail")
Solution 3:[3]
try this
user_email = all_data.get('user_email')
user_vmail = all_data.get('user_vmail')
or this
user_email = self.all_data.get('user_email')
user_vmail = self.all_data.get('user_vmail')
1st or 2nd will definitely fix that key error
Solution 4:[4]
Since you are using square brackets [] for keys it will throw KeyError if that key not exists in your all_data
class user_form(forms.Form):
user_email = forms.EmailField()
user_vmail = forms.EmailField()
def clean(self):
all_data = super().clean()
user_email = all_data['user_email'] #<---- throws key error if 'user_email' not in all_data
user_vmail = all_data['user_vmail'] #<---- throws key error if 'user_vmail' not in all_data
if user_email != user_vmail:
raise forms.ValidationError("Email Doesn't match")
So to avoid KeyError check for key if exists in your all_data as
class user_form(forms.Form):
user_email = forms.EmailField()
user_vmail = forms.EmailField()
def clean(self):
all_data = super().clean()
if not ('user_email' in all_data.keys() and 'user_vmail' in all_data.keys()):
raise forms.ValidationError("Please fill all fields.")
user_email = all_data['user_email']
user_vmail = all_data['user_vmail']
if user_email != user_vmail:
raise forms.ValidationError("Email Doesn't match")
Or to avoid KeyError use () as
user_email = all_data('user_email')
user_vmail = all_data('user_vmail')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akun.dev |
| Solution 2 | Lackson Munthali |
| Solution 3 | Ankit Tiwari |
| Solution 4 |

