Skip to content

Commit

Permalink
Prepare sirializers for REST API
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan committed May 2, 2023
1 parent aa5b373 commit 3a5c0bc
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.0.39] - 2023-05-02

### Added

- Prepare code for the UI improvements [@AivGitHub](https://github.com/AivGitHub/).

## [0.0.38] - 2023-04-11

### Added
Expand Down
75 changes: 75 additions & 0 deletions api/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from django.contrib.auth.models import update_last_login
from django.db.utils import IntegrityError
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.settings import api_settings

from accounts.models import User
from api.exceptions import UserAlreadyExists


class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
'id', 'username', 'email',
'first_name', 'last_name', 'is_active',
]
read_only_field = ['is_active']


class SignInSerializer(TokenObtainPairSerializer):

def validate(self, attrs):
data = super().validate(attrs)
token = self.get_token(self.user)

data['user'] = UserSerializer(self.user).data
data['refresh'] = str(token)
data['access'] = str(token.access_token)

if api_settings.UPDATE_LAST_LOGIN:
update_last_login(None, self.user)

return data


class SignUpSerializer(UserSerializer):
username = serializers.CharField(
max_length=64,
min_length=3,
write_only=True,
required=True
)
first_name = serializers.CharField(
max_length=150,
min_length=3
)
last_name = serializers.CharField(
max_length=50,
min_length=3
)
password = serializers.CharField(
max_length=128,
min_length=8,
write_only=True,
required=True
)
email = serializers.EmailField(
max_length=254,
write_only=True,
required=True
)

class Meta:
model = User
fields = [
'username', 'password', 'email',
'first_name', 'last_name', 'is_active',
]

def create(self, validated_data):
try:
return User.objects.create_user(**validated_data)
except IntegrityError:
raise UserAlreadyExists()

0 comments on commit 3a5c0bc

Please sign in to comment.