You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

serializers.py 2.0 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 PublicUserSerializer(serializers.HyperlinkedModelSerializer):
  7. class Meta:
  8. model = User
  9. fields = (
  10. 'username',
  11. 'gravatar',
  12. settings.DRF_URL_FIELD_NAME,
  13. )
  14. extra_kwargs = {
  15. settings.DRF_URL_FIELD_NAME: {
  16. "view_name": "public-users:user-detail",
  17. },
  18. }
  19. class UserSerializer(serializers.HyperlinkedModelSerializer):
  20. class Meta:
  21. model = User
  22. fields = (
  23. 'username',
  24. 'email',
  25. 'gravatar',
  26. 'password',
  27. 'password_repeat',
  28. settings.DRF_URL_FIELD_NAME,
  29. )
  30. extra_kwargs = {
  31. settings.DRF_URL_FIELD_NAME: {
  32. "view_name": "users:user-detail",
  33. },
  34. }
  35. password = serializers.CharField(
  36. write_only=True,
  37. required=True,
  38. allow_blank=False,
  39. min_length=6,
  40. max_length=32,
  41. )
  42. password_repeat = serializers.CharField(
  43. write_only=True,
  44. required=True,
  45. allow_blank=False,
  46. min_length=6,
  47. max_length=32,
  48. )
  49. def create(self, validated_data):
  50. if validated_data['password'] != validated_data['password_repeat']:
  51. raise ValidationError(
  52. detail={
  53. "password_repeat": "Tow password doesn't match",
  54. }
  55. )
  56. validated_data.pop('password_repeat')
  57. password = validated_data.pop('password')
  58. user = super(UserSerializer, self).create(
  59. validated_data,
  60. )
  61. user.set_password(password)
  62. user.save()
  63. login(
  64. self.context['request'],
  65. user=user,
  66. backend=settings.AUTHENTICATION_BACKENDS[0],
  67. )
  68. return user