Guest User

Untitled

a guest
Aug 22nd, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. Difference between cleaned_data and cleaned_data.get in Django
  2. def clean_message(self):
  3. message = self.cleaned_data['message']
  4. num_words = len(message.split())
  5. if num_words < 4:
  6. raise forms.ValidationError("Not enough words!")
  7. return message
  8.  
  9. def clean(self):
  10. username = self.cleaned_data.get('username')
  11. password = self.cleaned_data.get('password')
  12. ...
  13. self.check_for_test_cookie()
  14. return self.cleaned_data
  15.  
  16. >>> cleaned_data = {'username': "bob", 'password': "secret"}
  17. >>> cleaned_data['username']
  18. 'bob'
  19. >>> cleaned_data.get('username')
  20. 'bob'
  21. >>> cleaned_data['foo']
  22. Traceback (most recent call last):
  23. File "<stdin>", line 1, in <module>
  24. KeyError: 'foo'
  25. >>> cleaned_data.get('foo') # No exception, just get nothing back.
  26. >>> cleaned_data.get('foo', "Sane Default")
  27. 'Sane Default'
Add Comment
Please, Sign In to add comment