create sender fix
This commit is contained in:
@@ -105,7 +105,7 @@ class CreateRouteSerializer(serializers.ModelSerializer):
|
||||
arrival = serializers.DateTimeField(source='arrival_DT')
|
||||
transport = serializers.ChoiceField(choices=type_transport_choices, source='type_transport')
|
||||
email_notification = serializers.BooleanField(source='receive_msg_by_email')
|
||||
contact_number = serializers.CharField(write_only=True)
|
||||
phone_number = serializers.CharField(write_only=True)
|
||||
owner_type = serializers.ChoiceField(choices=[('sender', 'Отправитель'), ('deliverer', 'Перевозчик')])
|
||||
|
||||
class Meta:
|
||||
@@ -156,14 +156,14 @@ class CreateRouteSerializer(serializers.ModelSerializer):
|
||||
|
||||
# проверяем существование городов в указанных странах
|
||||
try:
|
||||
City.objects.get(name=data['city_from'], country=country_from)
|
||||
city_from = City.objects.get(name=data['city_from'], country=country_from)
|
||||
except City.DoesNotExist:
|
||||
raise serializers.ValidationError({
|
||||
"city_from": f"Город '{data['city_from']}' не найден в стране {country_from}"
|
||||
})
|
||||
|
||||
try:
|
||||
City.objects.get(name=data['city_to'], country=country_to)
|
||||
city_to = City.objects.get(name=data['city_to'], country=country_to)
|
||||
except City.DoesNotExist:
|
||||
raise serializers.ValidationError({
|
||||
"city_to": f"Город '{data['city_to']}' не найден в стране {country_to}"
|
||||
@@ -172,33 +172,36 @@ class CreateRouteSerializer(serializers.ModelSerializer):
|
||||
return data
|
||||
|
||||
def create(self, validated_data):
|
||||
# получаем города и страны
|
||||
country_from = Country.objects.get(international_name=validated_data.pop('country_from'))
|
||||
country_to = Country.objects.get(international_name=validated_data.pop('country_to'))
|
||||
|
||||
from_city = City.objects.get(name=validated_data.pop('city_from'), country=country_from)
|
||||
to_city = City.objects.get(name=validated_data.pop('city_to'), country=country_to)
|
||||
|
||||
# обновляем номер телефона в профиле пользователя
|
||||
phone_number = validated_data.pop('phone_number')
|
||||
user_profile = get_object_or_404(UserProfile, user=self.context['request'].user)
|
||||
|
||||
# проверяем, не используется ли этот номер другим пользователем
|
||||
if UserProfile.objects.filter(phone_number=phone_number).exclude(user=self.context['request'].user).exists():
|
||||
raise serializers.ValidationError({
|
||||
"phone_number": "Этот номер телефона уже используется другим пользователем"
|
||||
})
|
||||
try:
|
||||
# получаем города и страны
|
||||
country_from = Country.objects.get(international_name=validated_data.pop('country_from'))
|
||||
country_to = Country.objects.get(international_name=validated_data.pop('country_to'))
|
||||
|
||||
user_profile.phone_number = phone_number
|
||||
user_profile.save()
|
||||
|
||||
# создаем маршрут
|
||||
route = Route.objects.create(
|
||||
from_city=from_city,
|
||||
to_city=to_city,
|
||||
owner=self.context['request'].user,
|
||||
**validated_data # owner_type приходит с фронта
|
||||
)
|
||||
|
||||
return route
|
||||
from_city = City.objects.get(name=validated_data.pop('city_from'), country=country_from)
|
||||
to_city = City.objects.get(name=validated_data.pop('city_to'), country=country_to)
|
||||
|
||||
# обновляем номер телефона в профиле пользователя
|
||||
phone_number = validated_data.pop('phone_number') # Удаляем из validated_data
|
||||
user_profile = get_object_or_404(UserProfile, user=self.context['request'].user)
|
||||
|
||||
# проверяем, не используется ли этот номер другим пользователем
|
||||
if UserProfile.objects.filter(phone_number=phone_number).exclude(user=self.context['request'].user).exists():
|
||||
raise serializers.ValidationError({
|
||||
"phone_number": "Этот номер телефона уже используется другим пользователем"
|
||||
})
|
||||
|
||||
user_profile.phone_number = phone_number
|
||||
user_profile.save()
|
||||
|
||||
# создаем маршрут
|
||||
route = Route.objects.create(
|
||||
from_city=from_city,
|
||||
to_city=to_city,
|
||||
owner=self.context['request'].user,
|
||||
**validated_data
|
||||
)
|
||||
|
||||
return route
|
||||
except Exception as e:
|
||||
raise
|
||||
|
||||
@@ -97,10 +97,18 @@ class AccountActionsView(ViewSet):
|
||||
@action(detail=False, methods=['post'])
|
||||
@handle_exceptions
|
||||
def create_route(self, request):
|
||||
serializer = CreateRouteSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
serializer.save()
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
print("[DEBUG] Входящие данные в create_route view:", request.data)
|
||||
try:
|
||||
serializer = CreateRouteSerializer(data=request.data, context={'request': request})
|
||||
if not serializer.is_valid():
|
||||
print("[DEBUG] Ошибки валидации:", serializer.errors)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
route = serializer.save()
|
||||
print("[DEBUG] Маршрут успешно создан в view:", route.id)
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
except Exception as e:
|
||||
print("[DEBUG] Необработанная ошибка в create_route:", str(e))
|
||||
raise
|
||||
|
||||
class CityView(ViewSet):
|
||||
|
||||
|
||||
Reference in New Issue
Block a user