django - 使用 cleaned_data 时如何修复 “TypeError: string indices must be integers”?

标签 django django-views

完整的回溯

response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio\accounts\views.py", line 129, in reset_activation_key email = form.cleaned_data['email'] TypeError: string indices must be integers

这是 View ,错误爆发的地方

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

最佳答案

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

关于django - 使用 cleaned_data 时如何修复 “TypeError: string indices must be integers”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44873070/

相关文章:

python - Django 中 Jinja 的标签 'raw' 抛出错误 - 'Did you forget to register or load this tag?'

python - 如何使用django在网站上存储静态文本

python - Django View 不返回 httpresponse

python-3.x - 为什么我的模型字段不读取其 ForeignKey 的值,而是返回其对象编号?

python - 在 Django 模板中包含 HTML 变量而不转义

django - 现在如何在Django中处理每个对象的权限?

python - 如何在 django 自定义用户模型中使用电子邮件或用户名登录用户

python - Django 线程评论系统

django - 如何获取 django 应用程序中所有 View 的列表?

python - 当子类LoginView时,Django 'NoneType'对象没有属性 'has_header'