Matt
Matt

Reputation: 2350

How do I encode the password for my user registration viewset in Django REST Framework?

I'm trying to add user registration functionality to my Django REST application.

Here is my serializer:

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

class UserSerializer(serializers.HyperlinkedModelSerializer):
    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)

    class Meta:
        model = User
        fields = ('url', 'id', 'username', 'password', 'email', 'snippets')

Here is my views:

from snippets.serializers import UserSerializer
from django.contrib.auth.models import User
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

Right now it's storing the password in plain text. How can I encode the password?

I would prefer to continue using the ViewSet classes as they're very clean and convenient.

Upvotes: 0

Views: 610

Answers (1)

Ykh
Ykh

Reputation: 7717

class UserCreateSerializer(ModelSerializer):
    def create(self, validated_data):
        instance = User.objects.create_user(**validated_data)
        return instance

    class Meta:
        model = User
        fields = ('username', 'email', 'password')



class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserCreateSerializer
    permission_classes = (IsAuthenticated)

    def get_permissions(self):
        if self.action in ('create',):
            self.permission_classes = [AllowAny, ]
        return super(self.__class__, self).get_permissions()

    def create(self, request, *args, **kwargs):
        serializer = UserCreateSerializer(data=request.data)  
        if serializer.is_valid():
            user = serializer.create(serializer.validated_data)
            return Response('success')
        else:
            return Response(serializer.errors)

User.objects.create_user() will encode your password with django default encryption algorithm(PBKDF2).And you can use make_password to change your origin password to encoded one,or you can use user.set_password(request.data['pwd_new'])

from django.contrib.auth.hashers import make_password

more info here

Upvotes: 2

Related Questions