set_password() 在 Django Serializer create() 函数中不起作用

发布于 2025-01-11 07:19:08 字数 1905 浏览 0 评论 0原文

我针对我的问题尝试了所有现有的解决方案,但没有一个有效。

该代码通过邮递员运行良好,但密码未在 SQLite 表中进行哈希处理。

如下:

models.pyviews.pyserializers.py

from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    class Role(models.IntegerChoices):
        SUPERUSER = 1
        ADMIN = 2
        MANAGEMENT = 3
        HEAD = 4
        TRAINEE = 5
        PROVIDER = 6
        TRAINER = 7

    role = models.IntegerField(null=False, verbose_name='role', choices=Role.choices, default=Role.TRAINEE)
    email = models.EmailField(unique=True, max_length=255, verbose_name='email')
    password = models.CharField(max_length=255, verbose_name='password')
    username = None

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['role']

from django.shortcuts import render
from rest_framework.views import APIView
from .serializers import UserSerializer
from rest_framework.response import Response


class RegisterView(APIView):
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

代码

from rest_framework import serializers
from .models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'email', 'password', 'role']
        extra_kwargs = {
            'password': {'write_only': True}
        }

        # validate_password = make_password

        def create(self, validated_data):
            password = validated_data.pop('password')
            instance = self.Meta.model(**validated_data)
            if password is not None:
                instance.set_password(password)
            instance.save()
            return instance

如果您可以支持我提供解决方案

I tried all existing solutions for my issue and none worked.

The code is working well through postman, yet the password in not hashed in SQLite table.

The code is as follows:

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    class Role(models.IntegerChoices):
        SUPERUSER = 1
        ADMIN = 2
        MANAGEMENT = 3
        HEAD = 4
        TRAINEE = 5
        PROVIDER = 6
        TRAINER = 7

    role = models.IntegerField(null=False, verbose_name='role', choices=Role.choices, default=Role.TRAINEE)
    email = models.EmailField(unique=True, max_length=255, verbose_name='email')
    password = models.CharField(max_length=255, verbose_name='password')
    username = None

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['role']

views.py

from django.shortcuts import render
from rest_framework.views import APIView
from .serializers import UserSerializer
from rest_framework.response import Response


class RegisterView(APIView):
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

serializers.py

from rest_framework import serializers
from .models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'email', 'password', 'role']
        extra_kwargs = {
            'password': {'write_only': True}
        }

        # validate_password = make_password

        def create(self, validated_data):
            password = validated_data.pop('password')
            instance = self.Meta.model(**validated_data)
            if password is not None:
                instance.set_password(password)
            instance.save()
            return instance

Please if you may support me with a solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾北清歌寒 2025-01-18 07:19:08

此代码中的错误在于 create() 函数在 Meta 类下缩进。

Create() 必须位于 UserSerializer() 类下。

The error in this code is that the create() function is indented under the Meta Class.

Create() must be under the UserSerializer() Class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文