9
9
95506682020-11-30 13:38:52
Django
9550668, 2020-11-30 13:38:52

How to remove required_field in Serializer?

Hello everybody!

I am writing a user data change class.

The code is the following:

class UsersUpdateAPIView(generics.UpdateAPIView, UserCustomMixin):
    '''
    USERS Update data class
    Data to update:
    * fullname,
    * email,
    * date_of_birth,
    * avatar
    '''

    serializer_class = UsersSerializer
    queryset = Users.objects.all()

    def put(self, request, *args, **kwargs):
        response_data = {}
        response_status = 200

        serializer = UsersSerializer(data=request.data)

        if serializer.is_valid():
            print(serializer.data)
        else:
            print(serializer.errors)

        return JsonResponse(response_data, status=response_status)


Model:
class Users(AbstractBaseUser):
    username = models.CharField(
        max_length=50,
        unique=True,
        validators=[
            RegexValidator(
                regex= USERNAME_REGEX,
                message='Username field can only be Alphanameric or contain additional ., _, @, +, -',
                code='invalid_username')]
    )

    email = models.EmailField(
        verbose_name='email address',
        max_length=155,
        unique=True,
        blank=True
    )

    mobile = models.CharField(
        unique=True,
        max_length=50,
        verbose_name="Mobile phone number",
        validators=[
            RegexValidator(
            regex=MOBILE_REGEX,
            message='Wrong mobile number sequence',
            code='Invalid mobile number')]
    )

    fullname = models.CharField(
        max_length = 100,
        verbose_name = "Name and Surname",
        default="",
        blank=True
    )

    avatar = models.ForeignKey(UsersAvatar, on_delete=models.SET_NULL, null=True, default=None)

    country_code = models.IntegerField(verbose_name="Country", default=1)

    date_of_birth = models.DateField(blank=True, default="2000-01-01")

    registered_date = models.DateTimeField(auto_now_add=True)

    last_seen = models.DateTimeField(auto_now=True)

    is_active = models.BooleanField(default=True)

    is_worker = models.BooleanField(default=False)

    is_admin = models.BooleanField(default=False)

    objects = UsersManager()

    USERNAME_FIELD = 'mobile'


When submitting a change request via Postman, 'fullname' throws an error:
{'username': [ErrorDetail(string='This field is required.', code='required')]}

But username is set on creation. Why does he ask him to change any data? I tried passing the current username value, also an error, but 'unique' (taking into account the requirement for the username field in the model).

Tell me, please, how to fix it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question