I am working on API Validation Errors to be called. I have to make sure 2 dates don't overlap when making new "POST" calls, which is working fine. I am doing a model.objects.Filter()
query and if anything gets returned, I return a validation error. However, I want to return this error only during POST requests. I have tried
if request.method == "POST":
do something
but I get errors under the "request" word saying "request" is not defined. is there another way to check the Method Type during validation? I am doing this in my serializer. Thanks!
CodePudding user response:
You can pass request context to serializer from your view:
serializer = SomeSerializer(context={'request':request}, data=request.data)
In your serializer, you can access the request method as:
self.context['request'].method
CodePudding user response:
Use more than one serializer and redefine get_serializer_class
a drf function under your view
def get_serializer_class(self):
if self.request.method == 'POST':
return PostSerializer
return OtherMethodsSerializer