简体   繁体   中英

Dealing with multiple POST requests in Django views

I would like to know if it is possible to handle different POST requests in a Django view method. For example, take the following code:

def my_view(request):
    if request.method == "POST":
        if request.POST['value_one']:
            # Do stuff here

        elif request.POST['value_two']:
            # Do stuff here

        elif request.POST['value_three']:
            # Do stuff here

        else:
            # Do something else

Is it possible to do something like this within a Django view? If not, then what would be the best approach to handle such a situation?

Technically this is not "Dealing with multiple post requests" (which is kind of a nonsense - a view will only handle one single request - whatever the method - at a time), but "handling different values from a post request" (or from a GET request FWIW, it doesn't change much).

Now to answer your question: yes of course it is possible - as you would find out if you tried by yourself -, and is a rather common pattern. You just may want to use request.POST.get("whatever", default) instead to avoid having to deal with KeyError when some key is not part of the request's body (POST) or querystring (GET).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM