how to discriminate based on HTTP method in django urlpatterns

前端 未结 2 781
小鲜肉
小鲜肉 2020-12-29 22:02

I\'m having some difficulties finding information about this, probably it\'s not the right approach. I\'d like to route a request to two different view functions based on th

2条回答
  •  孤城傲影
    2020-12-29 23:08

    I don't think you can do this with different functions without adding a bunch of logic to the URL (which is never a good idea), but you can check inside the function for the request method:

    def myview(request):
        if request.method == 'GET':
            # Code for GET requests
        elif request.method == 'POST':
            # Code for POST requests
    

    You could also switch to class-based views. You would then only need to define a method for each of the HTTP methods:

    class CreateMyModelView(CreateView):
        def get(self, request, *args, **kwargs):
            # Code for GET requests
    
        def post(self, request, *args, **kwargs):
            # Code for POST requests
    

    If you decide to go the class-based route, another good resource is http://ccbv.co.uk/.

提交回复
热议问题