Django api с пользовательской аутентификацией пользовательского приложения

Я создал проект django, который использует customUser для аутентификации, следуя этой записи в блоге.

Теперь я хочу присоединить к проекту другое приложение, которое является REST API и использует эту аутентификацию.

<
#project/api/models.py
from django.contrib.postgres.fields import ArrayField
from django.db import models

from accounts.models import CustomUser


class Signal(models.Model):
    name = models.CharField(max_length=30, blank=True, null=True)
    data = ArrayField(models.FloatField(), unique=True)
    threshold = models.FloatField(blank=True, null=True)
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

    def __str__(self) -> str:
        return f"{self.name}"

пока project/api/views.py файл является

from django.template.defaultfilters import pluralize
from rest_framework.decorators import api_view
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response

from . import serializers
from .algorithm.compute_crossing import count_crossing_pos as count_cross
from .models import Signal


class SignalViewset(ListCreateAPIView):
    permission_classes = [IsAuthenticated]
    queryset = Signal.objects.all()
    serializer_class = serializers.SignalSerializer

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)


class SignalDetail(RetrieveUpdateDestroyAPIView):
    permission_classes = [IsAuthenticated]
    queryset = Signal.objects.all()
    serializer_class = serializers.SignalSerializer

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)


@api_view(http_method_names=["POST"])
def send_data(request: Request) -> Response():
    """send signal data with threshold in request payload
    and compute crossing times around given threshold
    :param request: [request payload]
    :type request: [type]
    """
    if request.user.is_authenticated:
        count = count_cross(request.data.get("data"), request.data.get("threshold"))
        return Response(
            {
                "status": "success",
                "info": "signal crosses the given threshold {} tim{}".format(
                    count, pluralize(count, "e,es")
                ),
                "count": str(count),
            },
            status=200,
        )
    else:
        count = count_cross(request.data.get("data"), request.data.get("threshold"))
        return Response(
            {
                "status": "success",
                "info": "you are an  AnonymousUser but I will give you an answer nonetheless \n \n signal crosses the given threshold {} tim{}".format(
                    count, pluralize(count, "e,es")
                ),
                "count": str(count),
            },
            status=200,
        )

Каждый раз, когда я обращаюсь к конечной точке send_data, я попадаю в оператор else, так как request.user.is_authenticated является False. как мне соединить rest api с приложением аутентификации (учетные записи)?

мой settings.py файл:

Вернуться на верх