Amir reza Riahi
Amir reza Riahi

Reputation: 2460

How give 2 parameter in PUT method?

I have a model of books with name and id. I want to change the name using PUT method requests, but I don't know how to handle put requests in django. I want to receive 2 parameter in PUT request: new name and id. the older name will be replaced by new name but the id won't change. this is my incomplete function:

def change_book_name(request):

    put = QueryDict(request.body)
    new_name = put.get("name")

Upvotes: 1

Views: 715

Answers (2)

Wariored
Wariored

Reputation: 1343

Try this:

from django.http import QueryDict
    if request.method == "PUT":
            put = QueryDict(request.body)
            key = put.get("key")

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

The QueryDict that wraps over the request.body is request.POST (regardless whether it is a GET, PUT, POST, PATCH, etc. request). What you here aim to do however, looks more like a PATCH request.

Anyway, you can simply obtain two parameters from the querydict, and update the item. For example with:

from django.http import JsonResponse
from django.views.decorators.http import require_http_methods

@require_http_methods(['PUT'])
def change_book_name(request):
    if 'name' in request.POST and 'id' in request.POST:
        new_name = request.POST['name']
        id = request.POST['id']
        MyModel.objects.filter(pk=id).update(name=new_name)
        return JsonResponse({'status': 'success'})
    return JsonResponse({'status': 'failure'})

Where you should replace MyModel and name with the correct model and field to update.

Upvotes: 1

Related Questions