1

在我的 django 项目中,我使用 AbstractBaseUser 注册一个新用户。我使用 set_password 来定义他的密码,以便对其进行加密。现在我想创建一个用于编辑配置文件的视图。我希望密码能够更改和加密。我已经创建了一个视图,但是当我编辑它时,密码并没有在数据库中加密......这些是我的文件: models.py

class memberArea(AbstractBaseUser):
    username = models.CharField(max_length=255)
    email = models.EmailField(max_length=255, unique=True)
    phone = models.TextField()
    date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
    deliveryAddress = models.TextField()
    postalCode = models.CharField(max_length=255)
    forget = models.TextField(null=True, blank=True)
    city = models.CharField(max_length=255)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'phone', 'deliveryAddress', 'postalCode', 'city']

    objects = MyAccountManager()

serializers.py

from django.contrib.auth.hashers import make_password
                  ...

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = memberArea
        fields = ['username', 'email', 'phone', 'password', 'deliveryAddress', 'postalCode', 'city']
        extra_kwargs = {
            'password': {'write_only': True},
        }

        def validate_password(self, raw_password):
            return make_password(raw_password)

views.py

#Edit account
@api_view(['PUT', ])
def edit_account(request, pk):
    try:
        account = memberArea.objects.get(pk=pk)
    except memberArea.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'PUT':
        serializer = AccountSerializer(account, data=request.data)
        data = {}
        if serializer.is_valid():
            serializer.save()
            data['response'] = 'Account updated with success !'
            return Response(data)
        return Response(serializer.errors)

提前感谢您的帮助

4

0 回答 0