DRF - Custom serializer - prefill data by request.user

Viewed 43

I have a model:

class Income(...):
    user = ForeignKey(User....) # not null
    type = ...
    amount = ...

And a special non-model serializer that should (besides other things) create Income objects for this user.

class WelcomeWizardSerializer(serializers.Serializer):
    applicant = serializers.HiddenField(default=serializers.CurrentUserDefault())
    applicant_incomes = IncomeSerializer(many=True, required=True)

Obviously, I need to tell IncomeSerializer to use applicant as user. Otherwise WelcomeWizardSerializer returns errors:

{'applicant_incomes': [{'user': [ErrorDetail(string='Toto pole je povinné.', code='required')]}, {'user': [ErrorDetail(string='Toto pole je povinné.', code='required')]}]}

How can I do that?

@action(['POST'], detail=False, url_path='from-welcome-wizard')
def from_welcome_wizard(self, request, pk=None):
    serializer = WelcomeWizardSerializer(context={'request':request}, data=request.data)
    if serializer.is_valid(): # not valid
        serializer.save()

I know I should get applicant (as I don't want to use CurrentUserDefault in IncomeSerializer) and add it to the data['incomes'] objects but I don't know where/when is the right place/time.

1 Answers

As you can see from the error message, you have an issue with WelcomeWizardSerializer.applicant_incomes, not WelcomeWizardSerializer.applicant. WelcomeWizardSerializer.applicant is all right.

Apparently, you have a user field inside applicant_incomes, and you don't want a client to pass a user into it as well. So you need to replace IncomeSerializer with some new serializer, for example, IncomeDefaultUserSerializer. You will need a similar HiddenField inside it, like:

user = serializers.HiddenField(default=serializers.CurrentUserDefault())

After that, you have to use IncomeDefaultUserSerializer inside WelcomeWizardSerializer, and your issue has to be solved.

Related