【问题标题】:Django error: 'NoneType' object is not subscriptableDjango 错误:“NoneType”对象不可下标
【发布时间】:2010-08-20 19:11:54
【问题描述】:

制作这个简单的表格花了我很长时间。快到了,但是当我提交时,我得到了 NoneType 错误

views.py:

from djangoproject1.authentication import forms
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def main(request):
    rf = forms.RegisterForm()
    pf = forms.ProfileForm()
    return render_to_response("authentication/index.html", {'form1': rf, 'form2':pf})

def register(request):
    if request.method == 'POST':
        rf = forms.RegisterForm(request.POST)
        pf = forms.ProfileForm(request.POST)
        if rf.is_valid() and pf.is_valid():
            newuser = User(username=rf.cleaned_data['username'],email=rf.cleaned_data['email']) # this is the offending line
            newuser.set_password(rf.cleaned_data['password'])
            newuser.save()
            profile = pf.save(commit=False)
            profile.user = newuser
            profile.save()
            return HttpResponseRedirect("/register-success/")
    else: 
        return main(request)

forms.py:

from django import forms
from djangoproject1.authentication.models import UserProfile    

class RegisterForm(forms.Form):
    username = forms.CharField(min_length=6,max_length=15)
    password = forms.CharField(min_length=6,max_length=15,widget = forms.PasswordInput())
    cpassword = forms.CharField(label='Confirm Password',widget = forms.PasswordInput())
    email = forms.EmailField(label='E-mail Address')

    def clean(self):
        if self.cleaned_data['cpassword']!=self.cleaned_data['password']:
            raise forms.ValidationError("Passwords don't match")

class ProfileForm(forms.ModelForm):
    phonenumber = forms.CharField(label='Phone Number')

    class Meta:
        model = UserProfile
        exclude = ('user')

堆栈跟踪:

Environment:

Request Method: POST
Request URL: http://localhost:8000/register/
Django Version: 1.2.1
Python Version: 2.7.0
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'djangoproject1.authentication']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  100.                     response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\jec23\My Java Projects\djangoproject1\src\djangoproject1\..\djangoproject1\authentication\views.py" in register
  21.             newuser = User(username=rf.cleaned_data['username'],email=rf.cleaned_data['email'])

Exception Type: TypeError at /register/
Exception Value: 'NoneType' object is not subscriptable

【问题讨论】:

  • 你能发布错误的堆栈跟踪吗?
  • 已发布堆栈跟踪。除了显示错误的来源之外,它并没有多大帮助。

标签: django django-models django-forms


【解决方案1】:

如果没有引发错误,forms.py 中的 clean 方法应该返回 self.cleaned_data

目前,它返回 None(因为您没有明确返回任何内容)

【讨论】:

  • 谢谢,就是这样。我没有意识到我必须返回cleaned_data。
【解决方案2】:

按照这一行的内容:

newuser = User(username=rf.cleaned_data['username'],email=rf.cleaned_data['email'])

在我看来,表单实例rf 没有cleaned_data 字段。当您尝试访问 cleaned_data 时可能会引发 'NoneType' object is unsubscriptable 错误,就像访问字典一样,但 cleaned_data 实际上是 None

要检查(相当笨拙)在违规行之前添加print 语句:

print rf.cleaned_data

好的。仔细一看,这很可能是罪魁祸首:

def clean(self):
    if self.cleaned_data['cpassword']!=self.cleaned_data['password']:
        raise forms.ValidationError("Passwords don't match")

Clean 方法应显式返回cleaned_data。由于这不是,因此会导致错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 2013-01-13
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多