Prometheus
Prometheus

Reputation: 33625

Django Forms: list indices must be integers, not str

Could anyone help explain the following error and what it means in relation to the code below?

All I'm trying to do is save a form.

error

    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

views.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))

models.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)

forms.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.")

updated def clean

  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")

Upvotes: 0

Views: 2451

Answers (2)

pemistahl
pemistahl

Reputation: 9584

In line 17 in your views.py it says:

form = RegistrationForm

Instead, it should rather be

form = RegistrationForm()

The source of your error is probably something different, but I just wanted to mention it.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

I wish you had posted the full traceback, then it would have been much easier to solve your problem.

However I guess it is because you are randomly returning things in your clean function. You have return cleaned_data at one point, but then after that you have return username. You do need to return cleaned_data from this function, but you should be doing at the end, otherwise you will never actually get to the second validator.

Upvotes: 2

Related Questions