Anuj
Anuj

Reputation: 1200

Django forms - dictionary and lists

I have created a django form having following fields:

class MyForm(forms.Form):
    name = forms.CharField(required=True)
    type = forms.CharField(required=True)
    username = forms.CharField(required=True)
    password = forms.CharField(required=True)

Now when I do a cleaned data in my view:

form = MyForm(request.REQUEST)
data = form.cleaned_data

The data is a dictionary with each of the form fields. For eg.

data = {
   "name": "ABC",
   "type": "Testing",
   "username":"abc",
   "password":"abc"
}

I want that some of the fields are part of the dictionary inside the main data dictionary. For eg.

data = {
   "name": "ABC",
   "type": "Testing",
   "user": {
       "username":"abc",
       "password":"abc"
   }
}

Upvotes: 1

Views: 4052

Answers (1)

Alasdair
Alasdair

Reputation: 309029

The form.cleaned_data dictionary is flat. You can take that and create whatever data structure you want.

cleaned_data = form.cleaned_data
nested_data = {
    'name': cleaned_data['name'],
    ...
    'user': {
        'username': cleaned_data['username'],
        'password': cleaned_data['password'],
    }
}

Upvotes: 2

Related Questions