Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between cleaned_data and cleaned_data.get in Django

Tags:

django-forms

I've seen some samples codes like:

def clean_message(self):
    message = self.cleaned_data['message']
    num_words = len(message.split())
    if num_words < 4:
        raise forms.ValidationError("Not enough words!")
    return message

and some examples like:

def clean(self):
    username = self.cleaned_data.get('username')
    password = self.cleaned_data.get('password')
    ...
    self.check_for_test_cookie()
    return self.cleaned_data

What's the difference between the two?

like image 486
Ricky Gu Avatar asked Sep 29 '11 04:09

Ricky Gu


2 Answers

.get() is basically a shortcut for getting an element out of a dictionary. I usually use .get() when I'm not certain if the entry in the dictionary will be there. For example:

>>> cleaned_data = {'username': "bob", 'password': "secret"}
>>> cleaned_data['username']
'bob'
>>> cleaned_data.get('username')
'bob'
>>> cleaned_data['foo']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'foo'
>>> cleaned_data.get('foo')  # No exception, just get nothing back.
>>> cleaned_data.get('foo', "Sane Default")
'Sane Default'
like image 182
Jack M. Avatar answered Sep 21 '22 18:09

Jack M.


cleaned_data is a Python dictionary, you can access its values by:

Specifying the key between [ ]:

 self.cleaned_data[‘field’]

Using get() method:

self.cleaned_data.get(‘field’)

Difference between cleaned_data and cleaned_data.get in Django is that if the key does not exist in the dictionary, self.cleaned_data[‘field’] will raise a KeyError, while self.cleaned_data.get(‘field’) will return None.

like image 36
imsaiful Avatar answered Sep 18 '22 18:09

imsaiful