How to fix "TypeError: string indices must be integer" when using cleaned_data?
full trace
response = wrapped_callback (request, * callback_args, ** callback_kwargs) File "C: \ Users \ PANDEMIC \ Desktop \ td11 \ newstudio \ accounts \ views.py", line 129, in reset_activation_key email = form.cleaned_data ['email'] TypeError: string indices must be integers
this is the kind where the bug explodes
def reset_activation_key(request):
if request.user.is_authenticated():
return redirect('/accounts/logout')
if request.method == "POST":
form = ResetActivatioKey(request.POST or None)
if form.is_valid():
email = form.cleaned_data['email']
user = User.objects.get(email=email)
profile = UserProfile.objects.get(user=user)
if profile.is_active:
return redirect('/accounts/login')
if profile is not None and not profile.is_active == False :
username = user.username
email_path = "{0}/ResendEmail.txt".format(settings.EMAIL_FILE_PATH)
get_secret_key = activation_key_generator(username)
profile.activation_key = get_secret_key
profile.key_expires = (timezone.now() + datetime.timedelta(days=2)),
profile.save()
send_some_email(email, username, get_secret_key)
return redirect('/accounts/login')
else:
form = ResetActivatioKey()
context = {"form":form}
return render(request, 'accounts/registration/reset_activation_key.html', context)
shape
class ResetActivatioKey(forms.Form):
email = forms.EmailField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Email address"))
def clean(self):
try:
user = User.objects.get(email__iexact=self.cleaned_data['email'])
return self.cleaned_data['email']
except:
raise forms.ValidationError('User with that email does not exist!')
Clean
should return dict
. You need to rewrite the method Clean
:
def clean(self):
cleaned_data = super(ResetActivatioKey, self).clean()
try:
user = User.objects.get(email__iexact=self.cleaned_data['email'])
return cleaned_data
except:
raise forms.ValidationError('User with this email does not exist!')
source to share
Your method clean()
returns a string with the email address you just entered. You may need to call super()
in your method to get cleaned_data like dict
and return the same to the view.
You need to change your method clean()
in your form,
def clean(self):
cleaned_data = super(ResetActvatioKey, self).clean()
try:
user = User.objects.get(email__iexact=self.cleaned_data['email'])
return cleaned_data
except:
raise forms.ValidationError('User with that email does not exist!')
source to share