Django REST Framework:创建用户不需要密码,并且发送密码不会保存

时间:2018-10-25 02:03:58

标签: python django django-rest-framework

我正在使用DRF创建一个简单的注册/登录应用程序,在创建新用户时遇到输入密码的麻烦。

我已经浏览了SO和文档,但无法弄清楚。

serializers.py

from django.contrib.auth.models import User
from rest_framework.serializers import HyperlinkedModelSerializer


class UserSerializer(HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 
                  'groups', 'first_name', 'last_name',
                  'date_joined', 'last_login'
                 )
        write_only_fields = ('password',)

views.py

from django.contrib.auth.models import User, Group
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from rest_framework.generics import CreateAPIView
from .serializers import UserSerializer


class UserReadOnlyViewSet(ReadOnlyModelViewSet):
    """
    API endpoint that allows users to be viewed.
    """
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class UserCreateView(CreateAPIView):
    """
    API endpoint that allows users to be created.
    """
    serializer_class = UserSerializer

urls.py

from django.urls import path, include
from rest_framework import routers
from .views import UserReadOnlyViewSet, UserCreateView

router = routers.DefaultRouter()
router.register(r'users', UserReadOnlyViewSet)


urlpatterns = [
    path('', include(router.urls)),
    path('signup/', UserCreateView.as_view()),
]

我能够列出端点users/上的用户| users/<pk>/,并且可以通过将以下JSON数据发布到signup/来创建用户:

{
    "username": "new_user",
    "password": "12345678",
    "email": "fulano@dominio.com"
}

我还可以通过仅在请求正文中发送username来创建用户,并且我需要密码和用户名。

所以,总而言之,我遇到的问题

  1. 发布到signup/
  2. 时不需要密码
  3. 我发送的密码未保存,既不是哈希值也不是纯文本。

谢谢。

0 个答案:

没有答案