Reputation: 51
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!
Upvotes: 1
Views: 3016
Reputation: 51
From kamran890's suggestion, this is what I did on my serializer to do this validation only during a POST method call. Then other types of validation during other calls
if self.contect['request'].method == 'POST':
*do post validation*
else:
*do patch/put validation*
Upvotes: 0
Reputation: 1271
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
Upvotes: 1
Reputation: 842
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
Upvotes: 3