I'm using DRF to create a simple signup/login application and I am having trouble requiring the password when creating a new user.
I've lurked through SO and the documentation but haven't been able to figure this out.
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()),
]
I am able to list user(s) at the endpoint users/ | users/<pk>/, and I am able to create a user by posting to signup/, with the following JSON data:
{
"username": "new_user",
"password": "12345678",
"email": "fulano@dominio.com"
}
I am also able to create a user by sending only the username in the request body, and I need the password to be required, as is the username.
So, in summary the problems I am having are
- The password is not required when posting to
signup/ - When I send the password is not saved, neither hashed nor in plain-text.
Thank you.