Chau Loi
Chau Loi

Reputation: 1225

Django - How to take string values on URL for PUT?

I set up my URL like this :

path('voucher/<str:voucher_id>', views.update_voucher),

My process

def update_voucher(request, voucher_id):
    put = QueryDict(request.body)
    try: 
        customer_id = put.get('customer_id')
    except: 
        return HttpResponse("Missing parameters")
    updateVoucher = Voucher.objects.filter(code = voucher_id)

Its a PUT call taking parameters from both body and url. (voucher_id from URL) and (customer_id from body) .

I call this URL http://127.0.0.1:5448/voucher/NewVoucher

I got this error:

ValueError: Field 'id' expected a number but got 'NewVoucher'.

The below is my model: here.

class Voucher(models.Model):
    code = models.CharField(unique=True, max_length=255)
    delivery_type = models.CharField(max_length=255)
    description = models.CharField(max_length=255, blank=True, null=True)
    start_at = models.DateTimeField()
    end_at = models.DateTimeField()
    discount_type = models.CharField(max_length=255)
    discount_amount = models.FloatField(blank=True, null=True)

P/S: I am a maintainer - cant change method function, and cant change the way this URL take parameters from both URL and body

Upvotes: 0

Views: 187

Answers (1)

jeevu94
jeevu94

Reputation: 728

You are not passing voucher_id as integers. instead you are passing code "NewVoucher" which is a string as per this error.

ValueError: Field 'id' expected a number but got 'NewVoucher'.

You have to pass id in integers so it would look something like this

http://127.0.0.1:5448/voucher/1

So far as i've understood you are looking for filter based on voucher code i,e "NewVoucher". then Your method should be changed as,

def update_voucher(request, voucher_code, *args, **kwargs):
    voucher = get_object_or_404(Voucher, code=voucher_code)
    customer_id = request.data.get("customer_id")  # im not sure where you are using this customer_id
    if not customer_id:
        raise HttpResponse("Missing parameters")
    # updateVoucher = Voucher.objects.filter(code = voucher_id) no need of this line as voucher variable contains it


# urls
path('voucher/<str:voucher_code>', views.update_voucher),

Upvotes: 1

Related Questions