0

在我的 django 应用程序中,我需要使用电话号码检查用户是否存在。使用电话号码和 OTP 完成登录。我可以通过获取请求来检查用户是否存在

"/api/profiles/<primary key here>/".

但是,如果我要求

"/api/profiles/"

我得到了数据库中所有用户的列表。

如果请求,我需要我的应用程序不返回任何内容

"/api/profiles/"

和用户详细信息(如果要求)

"/api/profiles/<primary key here>/"

我该怎么做呢?

序列化器是基本模型序列化器


class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = [
            "id",
            "is_superuser",
            "fullname",
            "email",
            "is_staff",
            "is_active",
            # "birthdate",
            "phone_number",
            "created_at",
            "updated_at",
        ]

网址:


router = routers.DefaultRouter()
router.register(r"profiles", views.UserProfileViewSet)


urlpatterns = [
    path("admin", admin.site.urls),
    path("restauth/", include("rest_framework.urls", namespace="restauth")),
    path("api/", include(router.urls)),

意见:

class UserProfileViewSet(viewsets.ModelViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
4

2 回答 2

0

你能试试这个代码吗

from rest_framework import mixins

class UserProfileViewSet(viewsets.ViewSet, mixins.RetrieveModelMixin):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
于 2020-09-03T14:44:10.780 回答
0

我无法使用序列化程序找到任何答案。因此,我创建了一个基于函数的视图,该视图使用表单数据获取电话号码,并在每次发出请求且用户存在时将密码更新为随机的 6 位 otp。

检查用户:

try:
    UserProfiles.objects.get(phone_number=request.POST["phone_number"]
    # generate otp
    return HttpResponse(otp)
except:
    return HttpResponse("user not found")
于 2020-09-03T15:42:27.620 回答