我正在使用DRF创建一个简单的注册/登录应用程序,在创建新用户时遇到输入密码的麻烦。
我已经浏览了SO和文档,但无法弄清楚。
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',)
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
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
来创建用户,并且我需要密码和用户名。
所以,总而言之,我遇到的问题
signup/
谢谢。