1

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!

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect. I used: if self.contect['request'].method == 'POST': do validation Thanks alot!
Cool! If this or any other answer helped you to solve your problem, you may consider accepting it.
Thanks! I've accepted your answer
1

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

1 Comment

I'm sure this works, but I went with kamran890's suggestion first because it was easier to test! and that worked
0

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*

1 Comment

I will suggest you add this fix in your code, as a part of your question under EDIT section. That way @kamran890 can be credited for the answer and future viewers will be able to know the changes you did to your code to fix it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.