Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling Rest Api from Django admin Panel

My model has 2 values.One is URL and other one is price.When creating a new object via django admin panel.I want when i input URL in input field,a request should be sent to that specific URL and fetched the updated price for the field and populate it.I have gone through documentation and helping material but did not find help.Any help in this matter is highly appreciated. Thanks

like image 568
Abdur Rehman Avatar asked Apr 21 '17 06:04

Abdur Rehman


1 Answers

You can do something like this:

 import requests
 import json


class Model(model.Model):
    url=models.URLField()
    price=models.FloatField()

    def save(self, *args, **kwargs):
        resp = request.gets(self.url)
        #assuming that json response looks like this: {'price': 2000} 
        resp_str = resp.content.decode()
        resp_dict = json.loads(resp_str)
        self.price = resp_dict.get('price')
        super().save(*args, **kwargs)

note: The code is not tested, but it is enough to give a general idea to proceed further.

like image 68
javed Avatar answered Oct 24 '22 13:10

javed