Call Rest Api from the Django admin panel

My model has 2 values. One of them is the URL, and the other is the price. When creating a new object through the django admin panel. I want me to enter the URL in the input field, the request must be sent to this specific URL and the updated price for the field is displayed and fill it. I looked through the documentation and helped the material, but did not find help. Any help in this matter is much appreciated. thank

+4
source share
2 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 has not been verified, but this is enough to give a general idea of ​​the continuation.

+3
source

, , , .

models.py
class Testone(models.Model):
    url = models.URLField()
    price = models.DecimalField(max_digits=30,decimal_places=5)

admin.py
@admin.register(Testone)

class PriceAdmin(admin.ModelAdmin):
    fields = ['url']
    def save_model(self, request, obj, form, change):
        obj.price = poang.ikea_ru(request.POST['url'])['price'] # calls external function w/ the requests data. 
#function returns dict that why i use ['price'] to get a value from the dict
        super(PriceAdmin,self).save_model(request, obj, form, change)

, , .

0

Source: https://habr.com/ru/post/1675320/


All Articles