backend/passfinder/users/api/serializers.py

52 lines
1.4 KiB
Python
Raw Normal View History

2023-05-18 20:25:22 +03:00
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.generics import get_object_or_404
from passfinder.events.models import BasePoint
from passfinder.users.models import UserPreference
2023-05-18 20:25:22 +03:00
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
2023-05-21 20:46:07 +03:00
fields = ["username", "email"]
2023-05-18 20:25:22 +03:00
2023-05-21 20:46:07 +03:00
class UserRegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("username", "email", "password")
2023-05-18 20:25:22 +03:00
extra_kwargs = {
2023-05-21 20:46:07 +03:00
"password": {"write_only": True},
"email": {"required": True},
2023-05-18 20:25:22 +03:00
}
2023-05-21 20:46:07 +03:00
def create(self, validated_data):
user = User.objects.create(
username=validated_data["username"],
email=validated_data["email"],
)
user.set_password(validated_data["password"])
user.save()
return user
class UserPreferenceSerializer(serializers.ModelSerializer):
point = serializers.CharField(max_length=24, min_length=24)
class Meta:
model = UserPreference
fields = ["point", "type"]
def validate_point(self, val):
return get_object_or_404(BasePoint, oid=val)
def create(self, validated_data):
return UserPreference.objects.create(
user=self.context["request"].user, **validated_data
)