如何在APIView中设置密码-Django

时间:2019-02-19 06:37:25

标签: django django-models django-rest-framework django-views

我想设置我要保存数据的用户的密码。我试图设置注释行,但未设置注释行,并且出现错误set_password is not defined。如何设置我要保存在APIView中的实例的密码。

from rest_framework.views import APIView
from rest_framework import status
class EmployeeAddAPIView(APIView):

    def post(self, request, *args, **kwrgs):

        serializer1 = EmployeeRegisterSerializer(data=request.data)
        serializer2 = EmployeeProfileSerializer(data=request.data)

        user_role = ACLRoles.objects.get(id=4)

        if serializer1.is_valid():

            print(serializer1.validated_data['email'])
            # password = set_password(random_password)
            user = serializer1.save(
                username = serializer1.validated_data['email'],
                # password = password
            )

            if serializer2.is_valid():
                serializer2.save(
                    user_id = user.id,
                    user_company_id = self.request.auth.application.company.id,
                    user_role_id = user_role.id
                )

            print(serializer2.errors)

            return Response(serializer1.errors, serializer2.errors)

        return Response(serializer1.errors, serializer2.errors)

以前,在我的应用中,我设置的密码是这样的:

new_user = ur_form.save(commit=False)            
new_user.username = new_user.email
new_user.set_password(random_password)
new_user.save()

1 个答案:

答案 0 :(得分:2)

make_password调用django.contrib.auth.hashers link并在其中分配值的一种可能方法。就像

from django.contrib.auth.hashers import make_password

def post(self, request, *args, **kwrgs):

        serializer1 = EmployeeRegisterSerializer(data=request.data)
        serializer2 = EmployeeProfileSerializer(data=request.data)

        user_role = ACLRoles.objects.get(id=4)

        if serializer1.is_valid():

            print(serializer1.validated_data['email'])
            # password = set_password(random_password)
            user = serializer1.save(
                username = serializer1.validated_data['email'],
            )

            random_password = User.objects.make_random_password()
            obj = get_object_or_404(User, pk=user.id)
            obj.set_password(random_password)
            obj.save()

            if serializer2.is_valid():
                serializer2.save(
                    user_id = user.id,
                    user_company_id = self.request.auth.application.company.id,
                    user_role_id = user_role.id
                )

            print(serializer2.errors)

            return Response(serializer1.errors, serializer2.errors)

        return Response(serializer1.errors, serializer2.errors)