[Answered ]-How can I make generic View only accept POST or GET

1👍

Its already done for you since you’ve only provided a post method

From the docs

Because Django’s URL resolver expects to send the request and associated arguments to a callable function, not a class, class-based views have an as_view() class method which returns a function that can be called when a request arrives for a URL matching the associated pattern. The function creates an instance of the class and calls its dispatch() method. dispatch looks at the request to determine whether it is a GET, POST, etc, and relays the request to a matching method if one is defined, or raises HttpResponseNotAllowed if not

👤Sayse

1👍

You have to implement get method in view to handle get request. Else it will raise a 405 by default that means method not implemented. A class based view inherited from django.views.generic.view have to override all methods that should be implemented. In your case code may looks like below.

class CustomerInfoCheckView(LoginRequiredMixin, View):

def post(self, request, *args, **kwargs):
    # CustomerInfoForm by ajax request
    if request.is_ajax():
        form = CustomerInfoForm(
            request.POST,
        )

        if form.is_valid():
            return JsonResponse(
                data={
                    "valid": True,
                }
            )
        else:
            return JsonResponse(
                data={
                    "valid": False,
                    "errors": form.errors
                }
            )
def get(self, request, *args, **kwargs):
     raise Http404

You can raise 404, 405 or provide an error response with 405 as status code which will be more apt.

Leave a comment