"TypeError: string indices must be integers" when using cleaned_data

1.8k Views Asked by At

The error occurs here:

if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            clean = form.cleaned_data

            username = clean['username']
            email = clean['email']
            password = clean['password']
            new_user = User.objects.create_user(username, email, password)
            new_user.save()
            new_account = Account(user=new_user, email=email)
            new_account.save()

At the username = clean['username'] line. I've been able to use this exact line successfully in other places without issue. Why is it an issue now?

2

There are 2 best solutions below

0
On BEST ANSWER

You're probably returning the wrong thing from the form's clean() method - you should be returning the full self.cleaned_data dictionary.

1
On

Apparently cleaned_data is giving you a string, not a dictionary.

As a string can only be indexed by numbers, it's giving you this error.

Try printing the value to see what is going on.