使用cleaning_data时如何修复“TypeError:string indices必须是整数”?

时间:2017-07-02 16:45:22

标签: django django-views

完全追溯

  

response = wrapped_callback(request,* callback_args,   ** callback_kwargs)文件" C:\ Users \ P.A.N.D.E.M.I.C \ Desktop \ td11 \ newstudio \ accounts \ views.py",   第129行,在reset_activation_key中       email = form.cleaned_data [' email'] TypeError:字符串索引必须是整数

这是视图,其中错误爆发

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)

形式

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!')

2 个答案:

答案 0 :(得分:3)

Clean应该返回dict。您需要重写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!')    

答案 1 :(得分:3)

您的clean()方法返回一个字符串,其中包含您刚输入的电子邮件。您可能需要在方法上调用super()以将cleaning_data作为dict并将其返回到视图。

您需要在表单中修改clean()方法,

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!')