How can I access data in a Django form field from a view?

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 csv data value is stored in the list form field. From an external instance of testForm in the view, I want to see a list of .csv values ​​stored in the form field.

+3
source share
4 answers

What you usually do in django to get the form data will 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 formatting or data validation yourself, you can put this in the validation method on the form. Either for the entire form, or for the form field. This is also a great way to make your code drier.

+1
source

, cleaned_data is_valid. , - :

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

, , , . , !

+2

, .

-, , Python "self". :

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

Django . , - - , .

( form.is_valid()), cleaned_data:

    return self.cleaned_data['list']

, list - .

0

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

0
source

Source: https://habr.com/ru/post/1711199/


All Articles