我在本地运行我的 django rest 框架后端,它将充当社交媒体应用程序的后端。我正在通过向我的本地注册 url 发送一个 post 请求来测试将用户注册到我的后端,并在邮递员上使用以下 json 数据: “用户名”:“johndoe123”, “名字”:“约翰”, "last_name": "母鹿", “cuny_email”:“[email protected]”, “专业”:“经济学”, "CUNY": "猎人学院", “毕业年份”:2024 年, “出生日期”:“2023-05-02” 即使所有字段都已正确填写,我仍收到 400 错误请求。在邮递员中,我从后端收到以下回复 { “用户名”: [ “此字段是必需的。” ], “cuny_email”:[ “此字段是必需的。” ], “密码”: [ “此字段是必需的。” ], “确认密码”: [ “此字段是必需的。” ], “纽约市立大学”:[ “此字段是必需的。” ] }
这是我的 Registerserializer 类: 类 RegisterSerializer(序列化器.ModelSerializer): confirm_password = serializers.CharField(style = {'input_type':'password'}, write_only = True)
class Meta:
model = User
fields = ['username','first_name', 'last_name', 'cuny_email', 'password', 'confirm_password', 'major', 'CUNY', 'graduation_year', 'birth_date']
extra_kwargs = {
'password': {'write_only': True}
}
def save(self):
user = User(
username = self.validated_data['username'],
first_name = self.validated_data['first_name'],
last_name = self.validated_data['last_name'],
cuny_email = self.validated_data['cuny_email'],
major = self.validated_data['major'],
CUNY = self.validated_data['CUNY'],
graduation_year = self.validated_data['graduation_year'],
birth_date = self.validated_data['birth_date']
)
password = self.validated_data['password']
confirm_password = self.validated_data['confirm_password']
if not re.search(r'\.cuny\.edu$', self.validated_data.get('cuny_email')):
raise serializers.ValidationError("Must use a CUNY email to register")
if password != confirm_password:
raise serializers.ValidationError({'password': 'Passwords must match.'})
user.set_password(password)
user.save()
profile = UserProfile(
user=user,
#cuny_email=self.validated_data['cuny_email'],
major=self.validated_data.get('major'),
CUNY=self.validated_data.get('CUNY'),
birth_date=self.validated_data.get('birth_date')
)
profile.save()
return user
这是我的注册视图集: 类 RegisterViewset(viewsets.ModelViewSet): serializer_class = RegisterSerializer queryset = User.objects.all() #这行代码设置RegisterViewset的初始queryset包括数据库中的所有用户账户。 permission_classes = [permissions.AllowAny] # 设置谁可以访问RegisterViewset的权限为“allow any”,这意味着任何人都可以注册为新用户。 def create(self, request): #function 处理新用户帐户的创建 serializer = RegisterSerializer(data = request.data) # 使用用户注册时提交的请求数据创建 RegisterSerializer 类的新实例。
if serializer.is_valid():
user = serializer.save() #saves the new user account to the database.
#return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response({
"user": UserSerializer(user, context=self.get_serializer_context()).data, #
"token": AuthToken.objects.create(user)[1]
})
我更改了 json 字段以匹配后端预期字段的确切名称。我还重置了我的 django rest 框架服务器,并在我的本地 django rest 框架服务器中测试了发布请求,这似乎可以正常工作。但是,当我在邮递员中发送请求时,我仍然收到错误消息。