0

任何人都可以帮助解释以下错误及其与以下代码相关的含义吗?

我要做的就是保存一个表格。

错误

    TypeError at /member/registration/
    list indices must be integers, not str
/Users/user/Documents/workspace/Hera/member/views.py in registration, line 17

nvironment:


Request Method: POST
Request URL: http://127.0.0.1:8000/member/registration/

Django Version: 1.4.2
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.flatpages',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'grappelli.dashboard',
 'grappelli',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'web',
 'member',
 'rest_framework')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/user/Documents/workspace/Hera/member/views.py" in registration
  17.             user = User.objects.create_user(username=form.cleaned_data['username'],email=form.cleaned_data['email'], password=form.changed_data['password'])

Exception Type: TypeError at /member/registration/
Exception Value: list indices must be integers, not str

视图.py

def registration(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/error')
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(username=form.cleaned_data['username'],email=form.cleaned_data['email'], password=form.changed_data['password'])
            user.save()
            member = User.get_profile()
            member.name = form.cleaned_data['name']
            member.save()
            return HttpResponseRedirect('/profile')
        else:
            return render_to_response('pageRegistration.html', {'form':form},context_instance=RequestContext(request))

    else: 
        form = RegistrationForm 
        context = {'form':form}
        return render_to_response('pageRegistration.html', context, context_instance=RequestContext(request))

模型.py

class Member (models.Model):
    user =  models.OneToOneField(User)
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

def createUserCallBacks(sender, instance, **kwargs):
    member, new = Member.objects.get_or_create(user=instance)
post_save.connect(createUserCallBacks, User)

表格.py

class RegistrationForm(ModelForm):
    username = forms.CharField(label=(u'User Name'))
    email = forms.EmailField(label=(u'Email'))
    password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
    passwordConfirm = forms.CharField(label=(u'Confirm Password'), widget=forms.PasswordInput(render_value=False))

    class Meta:
        model = Member
        # Don't show user drop down.
        exclude = ('user',)



    def clean(self):
        cleaned_data = super(RegistrationForm, self).clean()
        try:        
            password = cleaned_data['password']
            passwordConfirm = cleaned_data['passwordConfirm']
            if password != passwordConfirm:
                raise forms.ValidationError("Password does not match, try again.")
            return cleaned_data
        except:
            raise forms.ValidationError("Password does not match, try again.")

        username = cleaned_data['username']
        try: User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError("Username already taken, try another.")

更新了定义清洁

  def clean(self):
        try:   
            cleaned_data = super(RegistrationForm, self).clean() 
            password = cleaned_data.get("password")
            passwordConfirm = cleaned_data.get('passwordConfirm')

            if password != passwordConfirm:
                raise forms.ValidationError("Password does not match, try again.")
            return cleaned_data
        except:
            raise forms.ValidationError("Error")
4

2 回答 2

2

我希望您已经发布了完整的回溯,那么解决您的问题会容易得多。

但是我想这是因为您在 clean 函数中随机返回了一些东西。你曾经有return cleaned_data过,但在那之后你有return username。你确实需要从这个函数返回cleaned_data,但你应该在最后做,否则你永远不会真正到达第二个验证器。

于 2012-12-17T10:41:07.080 回答
1

在您的views.py的第 17 行中,它说:

form = RegistrationForm

相反,它应该是

form = RegistrationForm()

您的错误的来源可能有所不同,但我只想提一下。

于 2012-12-17T10:45:14.397 回答