开发者问题收集

如何将自定义管理器类参数设置为 required=False

2020-03-11
147

我正在编写一个 API 来接受和保存用户个人资料信息。总共我想接受来自用户的 5 个参数,如下所示。

{
"first_name":"",
"last_name":"",
"email":"",
"password":"",
"profile_picture":""
}

在这 5 个参数中, first_namelast_nameemailpassword 是必需的,而 profile_picture 是可选的。

models.py 中,我将 profile_picture 称为 ImageField

models.py

class Users(AbstractBaseUser, PermissionsMixin):

    """
    This model is used to store user login credential and profile information.
    It's a custome user model but used for Django's default authentication.
    """

    email = models.EmailField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255, blank=False, null=False)
    last_name = models.CharField(max_length=255, blank=False, null=False)
    profile_picture = models.ImageField(upload_to='profile_picture/', max_length=None, blank=True)
    is_active = models.BooleanField(default=True)

    # defining a custom user manager class for the custom user model.
    objects = managers.UserManager()

    # using email a unique identity for the user and it will also allow user to use email while logging in.
    USERNAME_FIELD = 'email'

serializers.py 中,我将 profile_picture 称为 ImageField ,其中 required=False

serializers.py

class UserSerializer(serializers.Serializer):
    """
    This is a serializer class to validate create user request object.
    """
    class Meta:
        models = 'Users'

    email = serializers.EmailField(allow_blank=False)
    first_name = serializers.CharField(max_length=255, allow_blank=False)
    last_name = serializers.CharField(max_length=255, allow_blank=False)
    profile_picture = serializers.ImageField(max_length=None, allow_empty_file=True, use_url= False, required=False)
    password = serializers.CharField(
        max_length = 255,
        write_only=True,
        allow_blank = False,
        style={
            'input_type' : 'password'
        }
    )

    def create(self, validated_data):

        user_id = models.Users.objects.create_user(**validated_data)

        return user_id

这就是我的自定义管理器类的样子。

ma​​nager.py

class UserManager(BaseUserManager):
    """
    Manager class for the custome user manager. Every model has a default manager class.
    If you define a custome user model then model manager class also needs some customization. 
    """

    def create_user(self, email, first_name, profile_picture, last_name, password=None):
        """
        Here the default create_user() methode of the manager is overridden to achive customization.
        """

        # check email parameter is has some value ir its empty.
        if not email:

            # raise the value error if it is empty.
            raise ValueError('Users must have an email address.')

        # defining a model instance by mapping parameters with the model fields.
        user = self.model(
            # normalizing email i.e converting it to lower case.
            email = self.normalize_email(email),
            first_name = first_name,
            last_name = last_name,
            profile_picture = profile_picture,
            )
        # encrypting user password using default method set_password() 
        user.set_password(password)

        # saving instance in to model.
        user.save(using=self._db)

        # return model instance.
        return user

当我传递没有 profile_picture 的对象时,它会返回下面提到的错误。

TypeError at /user/create/
create_user() missing 1 required positional argument: 'profile_picture'

因此,我从管理器类的 create_user() 方法中删除 profile_picture 参数后再次尝试。但对于想要上传其 profile_picture 的用户来说,API 失败了。

3个回答

首先: 您需要保持图像字段的 null=True,因为 blank 用于前端验证,而 null 用于后端验证。

profile_picture = models.ImageField(upload_to='profile_picture/', max_length=None, blank=True, null=True)

其次,如果您想使 profile_picture 成为可选项,请将其设置为关键字参数。

def create_user(self, email, first_name, last_name, password=None,profile_picture=None):
danish_wani
2020-03-11

要将某些字段设置为非必填字段,您应该向其中添加 null=Trueblank=True ,因此请尝试在 models.py 中添加 null=True

profile_picture = models.ImageField(..., null=True)
Lothric
2020-03-11

您可以为个人资料照片设置一个默认值,直到用户更改它

profile_picture = models.ImageField(..., null=True, default="path/to/default/image.jpeg")
Newton Karanu
2020-03-11