Reputation: 2123
I'm running into an issue with a POST request. The field "employee" is required but I initialize it in the view (I set it to request.user), rather than in the request parameters. Yet I still get the following error:
data:
employee: ["This field is required."]
View
class EmployeeQuestionView(viewsets.ModelViewSet):
queryset = EmployeeQuestion.objects.all()
serializer_class = EmployeeQuestionSerializer
def perform_create(self, serializer):
serializer.save(employee=self.request.user)
Serializer
class EmployeeQuestionSerializer(serializers.ModelSerializer):
class Meta:
model = EmployeeQuestion
fields = (
'id',
'employee',
'question',
'attempted',
'passed',
)
Any ideas why?
Upvotes: 0
Views: 862
Reputation: 366
use read_only to ignore employee in validation
class EmployeeQuestionSerializer(serializers.ModelSerializer):
employee = serializers.SerializerMethodField(read_only=True)
class Meta:
model = EmployeeQuestion
fields = (
'id',
'employee',
'question',
'attempted',
'passed',
)
@staticmethod
def get_employee(obj):
return obj.employee
Upvotes: 1
Reputation: 1
I think it can be because you are not passing the request object to the function but trying to access the user through the request object.
Upvotes: 0