我正在设置Django rest API来访问我的银行帐户系统。 我的模型很好地序列化为JSON格式,除了我不知道如何像处理表单一样处理密码。请帮助。以下是我的相关文件。
我曾尝试在serializers.py中定义密码字段,但是当我运行项目时,它告诉我自定义User实例没有属性'password1',据我所知是正确的,因为AbstractUser没有名为password1和password2的属性。
accounts / models.py:
class User(AbstractUser):
email = models.EmailField(unique=True, blank=True, null=True)
contact_no = models.IntegerField(unique=False, null=True, blank=True)
account_no = models.PositiveIntegerField(
unique=True,
validators=[
MinValueValidator(1000000000),
MaxValueValidator(9999999999)
])
balance = models.DecimalField(
default=0,
max_digits=12,
decimal_places=2
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', ]
def __str__(self):
return str(self.full_name)
@property
def full_name(self):
return '{} {}'.format(self.first_name, self.last_name)
api / serializers.py:
class UserSerializer(RegisterSerializer):
password1 = serializers.CharField(
max_length=100,
style={'input_type': 'password', 'placeholder': 'Password'}
)
password2 = serializers.CharField(
max_length=100,
style={'input_type': 'password', 'placeholder': 'Confirm Password'}
)
class Meta:
model = User
fields = [
'first_name',
'last_name',
'email',
'contact_no',
'password1',
'password2',
]
api / views.py:
from rest_framework import generics
from accounts.models import User
from .serializers import UserSerializer
class UserCreateView(generics.ListCreateAPIView):
serializer_class = UserSerializer
queryset = User.objects.all()