Как разрешить метод POST в django API - PullRequest
0 голосов
/ 05 апреля 2020

Я застрял. Когда я пытаюсь использовать RideUserViewSet, я получаю по GET - «деталь»: «Не найдено». на POST-метод не допускается. Получить и удалить в порядке. Есть несколько поездок, где текущий пользователь является драйвером

urls.py

router = DefaultRouter()
router.register('rides', viewsets.RidePublicViewSet, basename="RidePublicViewSet")

user_rides_router = DefaultRouter()
user_rides_router.register('rides', viewsets.RideUserViewSet, basename="RideUserViewSet")

urlpatterns = [
    path('', include(router.urls)),
    path('users/', include(user_rides_router.urls)),
]

viewset.py

class RideUserViewSet(
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    mixins.CreateModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    viewsets.GenericViewSet
):
    permission_classes = (permissions.IsAuthenticated,)
    serializers = {
        'list': RideSerializer,
        'create': RideCreateSerializer,
        'retrieve': RideSerializer,
        'update': RideSerializer,
    }
    queryset = Ride.objects.all()
    filter_backends = [rest_filters.DjangoFilterBackend, filters.SearchFilter]
    filterset_class = ride_filters.RideFilter
    filterset_fields = ['price', 'date', 'point_a', 'point_b']
    search_fields = ['date', 'point_a', 'point_b']
    http_method_names = [ 'post','get', 'put', 'delete']

    def get_serializer_class(self):
        return self.serializers[self.action]

    def get_queryset(self, **kwargs):
        return self.queryset.filter(driver=self.request.user)

сериализаторов

class RideSerializer(serializers.ModelSerializer):
    driver = UserSerializer(read_only=True)
    passengers = PassengerSerializer(many=True, read_only=True)
    intermediate = IntermediateSerializer(many=True, read_only=True)

    class Meta:
        model = Ride
        fields = [
            'id',
            'date',
            'point_a',
            'intermediate',
            'point_b',
            'price',
            'seat',
            'vehicle',
            'note',
            'smoking_salon',
            'animals',
            'kids_seat',

            'driver',
            'passengers',
        ]

class RideCreateSerializer(serializers.Serializer):
    date = serializers.DateTimeField(write_only=True)
    point_a = serializers.CharField(write_only=True)
    point_b = serializers.CharField(write_only=True)
    price = serializers.DecimalField(max_digits=10, decimal_places=2)
    seat = serializers.IntegerField()
    note = serializers.CharField(required=False, allow_null=True)
    smoking_salon = serializers.BooleanField(default=False)
    animals = serializers.BooleanField(default=False)
    kids_seat = serializers.BooleanField(default=False)

    def create(self, validated_data):
        driver = self.context['request'].user

        create_ride = usecases.RideCreateUseCase()
        instance = create_ride(driver=driver, **validated_data)
        return instance

    def validate(self, validated_data):
        date = validated_data['date']
        seat = validated_data['seat']
        date_now = timezone.now().date()
        is_valid_date = date.date() < date_now

        if seat < 0:
            raise ValidationError(_('Unable to set less than 0'))
        if is_valid_date:
            raise ValidationError(_('Unable to set past date'))

        return validated_data

Использование ModelViewSet не помогает. та же проблема. Однажды я решил проблему с http_method_names, но не сейчас.

...