Last active
December 29, 2015 14:39
-
-
Save meoooh/7685757 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.auth.models import User | |
from django.utils.translation import ugettext as _ | |
from rest_framework import serializers | |
class UserSerializer(serializers.ModelSerializer): | |
password2 = serializers.CharField() | |
class Meta: | |
model = User | |
fields = ('username', 'password', 'password2') | |
def validate_password2(self, attrs, source): | |
if attrs.get('password') == attrs.pop('password2'): | |
return attrs | |
raise serializers.ValidationError( | |
_("The two password fields didn't match."), | |
code='password_mismatch', | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ./manage.py shell | |
Python 2.7.3 (default, Sep 26 2013, 20:03:06) | |
[GCC 4.6.3] on linux2 | |
Type "help", "copyright", "credits" or "license" for more information. | |
(InteractiveConsole) | |
>>> from app.serializers import * | |
>>> u=UserSerializer(data={'username':'test1','password':'pass','password2':'pas'}) | |
>>> u.errors | |
{'password2': [u"The two password fields didn't match."]} | |
>>> u=UserSerializer(data={'username':'test1','password':'pass','password2':'pass'}) | |
>>> u.errors | |
{} | |
>>> u.data | |
Traceback (most recent call last): | |
File "<console>", line 1, in <module> | |
File "/home/han/.virtualenvs/drf_test/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 537, in data | |
self._data = self.to_native(obj) | |
File "/home/han/.virtualenvs/drf_test/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 325, in to_native | |
value = field.field_to_native(obj, field_name) | |
File "/home/han/.virtualenvs/drf_test/local/lib/python2.7/site-packages/rest_framework/fields.py", line 198, in field_to_native | |
value = get_component(value, component) | |
File "/home/han/.virtualenvs/drf_test/local/lib/python2.7/site-packages/rest_framework/fields.py", line 56, in get_component | |
val = getattr(obj, attr_name) | |
AttributeError: 'User' object has no attribute 'password2' | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment