Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

61 rinda
1.6 KiB

  1. from django.conf import settings
  2. from django.contrib.auth import login
  3. from rest_framework import serializers
  4. from rest_framework.exceptions import ValidationError
  5. from users.models import User
  6. class UserSerializer(serializers.HyperlinkedModelSerializer):
  7. class Meta:
  8. model = User
  9. fields = (
  10. 'username',
  11. 'email',
  12. 'gravatar',
  13. 'password',
  14. 'password_repeat',
  15. settings.DRF_URL_FIELD_NAME,
  16. )
  17. extra_kwargs = {
  18. settings.DRF_URL_FIELD_NAME: {
  19. "view_name": "users:user-detail",
  20. },
  21. }
  22. password = serializers.CharField(
  23. write_only=True,
  24. required=True,
  25. allow_blank=False,
  26. min_length=6,
  27. max_length=32,
  28. )
  29. password_repeat = serializers.CharField(
  30. write_only=True,
  31. required=True,
  32. allow_blank=False,
  33. min_length=6,
  34. max_length=32,
  35. )
  36. def create(self, validated_data):
  37. if validated_data['password'] != validated_data['password_repeat']:
  38. raise ValidationError(
  39. detail={
  40. "password_repeat": "Tow password doesn't match",
  41. }
  42. )
  43. validated_data.pop('password_repeat')
  44. password = validated_data.pop('password')
  45. user = super(UserSerializer, self).create(
  46. validated_data,
  47. )
  48. user.set_password(password)
  49. user.save()
  50. login(
  51. self.context['request'],
  52. user=user,
  53. backend=settings.AUTHENTICATION_BACKENDS[0],
  54. )
  55. return user