views:

365

answers:

4

I have a simple Django Form:

class testForm(forms.Form):
  list = forms.CharField()

  def getItems(self):
    #How do I do this?  Access the data stored in list.
    return self.list.split(",") #This doesn't work

The list form field stores a csv data value. From an external instance of testForm in a view, I want to be able to look at the .csv value list stored in the form field.

A: 

There are a couple of things you need to know here.

First is that generally in a Python class method you access the attributes through the 'self' object. So in theory your function should be:

def get_items(self):
    return self.list.split(",")

However, in the case of a Django form, this won't work. This is because a field doesn't have a value of its own - the value is only attached to the field when it's rendered, and is obtained in different ways depending on whether the value was applied through initial data or by passing in a data dictionary.

If you have validated the form (through form.is_valid()), you can get the form via the cleaned_data dictionary:

    return self.cleaned_data['list']

However this will fail if list has failed validation for any reason.

Daniel Roseman
A: 

Call is_valid on the form, then access the cleaned_data dictionary.

phillc
+1  A: 

What you usually do in django in a view to get the form data would be something like this.

form = testForm(request.POST)
if form.is_valid:
    # form will now have the data in form.cleaned_data
    ...
else:
    # Handle validation error
    ...

If you want to do some data formatting or validation yourself you can put this in the validation method in the form. Either for the entire form or for a form field. This is also a great way to make your code more DRY.

googletorp
A: 

Like others have already mentioned, you need to make use of the form's cleaned_data dictionary attribute and the is_valid method. So you can do something like this:

def getItems(self):
    if not self.is_valid():
        return []    # assuming you want to return an empty list here
    return self.cleaned_data['list'].split(',')

The reason your method does not work is that the form fields are not your typical instance variables. Hope this helps!

atharh