发布名称,电子邮件和django后端的角色,react前端错误400

0s0u357o  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(113)

我想管理员发布名称,电子邮件和使用前端的用户的角色,其存储在后端的django,请注意,我不希望管理员存储密码,用户将稍后添加它.下面的代码是给错误400当我输入姓名,电子邮件和角色
djangocode:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserAccount
        fields = ['email', 'name', 'username', 'password', 'role']
    
    def create(self, validated_data):
        password = validated_data('password')
        username = validated_data('username')

        user = UserAccount(
            email=validated_data['email'],
            role=validated_data['role'],
            name=validated_data['name']
        )
        
        if username is not None:
            username=validated_data['username'],
          
        if password is not None:
            user.set_password(validated_data['password'])
            
        user.save()
        return user

React代码:

const handleSubmit = (event) => {
   event.preventDefault();
    const data = {
      name : name,
      email : email,
      role: role
    };

   console.log("data is "+data);
   axios.post('http://127.0.0.1:8000/api/register/', data)
    .then(response => console.log("got it"+response.data))
    .catch(error => console.log(error));

    console.log('name:', name);
    console.log('email:', email);
    console.log('role:', role);
jdg4fx2g

jdg4fx2g1#

给予这个:

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = UserAccount
        fields = ["email", "name", "username", "password", "role"]

    def validate_password(self, value):
        user = self.context["request"].user

        if user.role == "admin" and value is not None:  # mean admin is setting password
            raise serializers.ValidationError("Only user can set password")
        
        if user.role == "user" and value is None:  # Ask user to set password
            raise serializers.ValidationError("User must set password")

        return value

    # Your create method and other code

在这里,我们根据用户角色有条件地使字段成为必填字段。

相关问题