From db3c29d17ed9ee42b56f7d6d086524a4a40d7581 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9e=20Floure?= Date: Thu, 7 May 2020 12:05:26 +0200 Subject: [PATCH] Fix admin order creation --- .../uncloud/uncloud_pay/serializers.py | 32 +++++++++++++++++-- .../uncloud/uncloud_pay/views.py | 4 ++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/uncloud_django_based/uncloud/uncloud_pay/serializers.py b/uncloud_django_based/uncloud/uncloud_pay/serializers.py index 1b5db24..70f5c5e 100644 --- a/uncloud_django_based/uncloud/uncloud_pay/serializers.py +++ b/uncloud_django_based/uncloud/uncloud_pay/serializers.py @@ -1,5 +1,6 @@ from django.contrib.auth import get_user_model from rest_framework import serializers +from uncloud_auth.serializers import UserSerializer from .models import * ### @@ -41,11 +42,36 @@ class OrderRecordSerializer(serializers.ModelSerializer): class OrderSerializer(serializers.ModelSerializer): - records = OrderRecordSerializer(many=True, read_only=True) + owner = serializers.PrimaryKeyRelatedField(queryset=get_user_model().objects.all()) + + def __init__(self, *args, **kwargs): + # Don't pass the 'fields' arg up to the superclass + admin = kwargs.pop('admin', None) + + # Instantiate the superclass normally + super(OrderSerializer, self).__init__(*args, **kwargs) + + # Only allows owner in admin mode. + if not admin: + self.fields.pop('owner') + + def create(self, validated_data): + billing_address = BillingAddress.get_preferred_address_for(validated_data["owner"]) + instance = Order(billing_address=billing_address, **validated_data) + instance.save() + + return instance + + def validate_owner(self, value): + if BillingAddress.get_preferred_address_for(value) == None: + raise serializers.ValidationError("Owner does not have a valid billing address.") + + return value + class Meta: model = Order - fields = ['uuid', 'creation_date', 'starting_date', 'ending_date', - 'bill', 'recurring_period', 'records', 'recurring_price', 'one_time_price'] + fields = ['uuid', 'owner', 'creation_date', 'starting_date', 'ending_date', + 'bill', 'recurring_period', 'recurring_price', 'one_time_price'] ### diff --git a/uncloud_django_based/uncloud/uncloud_pay/views.py b/uncloud_django_based/uncloud/uncloud_pay/views.py index 0c68ac6..54ff2f0 100644 --- a/uncloud_django_based/uncloud/uncloud_pay/views.py +++ b/uncloud_django_based/uncloud/uncloud_pay/views.py @@ -279,9 +279,11 @@ class AdminBillViewSet(viewsets.ModelViewSet): return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) class AdminOrderViewSet(viewsets.ModelViewSet): - serializer_class = OrderSerializer permission_classes = [permissions.IsAuthenticated] + def get_serializer(self, *args, **kwargs): + return OrderSerializer(*args, **kwargs, admin=True) + def get_queryset(self): return Order.objects.all()