[Django]-Handle OPTIONS request with django's built in server

7๐Ÿ‘

โœ…

I would suspect that OPTIONS request is returning a 405 error because an options handler hasnโ€™t been defined in your view class. Note that Django does not provide a default options handler.

Here is the code (django source code) that is responsible for calling the appropriate methods on your class:

# snippet from  django.views.generic.base.View

http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

def dispatch(self, request, *args, **kwargs):
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

options is one of the default http method that can be handled in Django view. If the options handler hasnโ€™t been defined, the dispatch method returns a 405 error.


Here is an example of options method

class TheView(View):
    
    self.allowed_methods = ['get', 'post', 'put', 'delete', 'options']
    def options(self, request, id):
        response = HttpResponse()
        response['allow'] = ','.join([self.allowed_methods])
        return response
๐Ÿ‘คDerek Kwok

0๐Ÿ‘

To create a valid preflight check you can set up your own CORS Anywhere server or use a managed server like Just CORS as a reverse prop with added CORS headers.

๐Ÿ‘คHerman Martinus

Leave a comment