[Django]-Django and post request to an external API in different views

8👍

First add an action attribute and method attribute to your form. Then add a csrf token for security. Also add name attributes to the select elements.

<form method="post" action="/external" id="formdata" >
  {% csrf_token %}
<select name="options" id="options">
    <option id="sku">Option 1</option>
    <option id="sku2">Option 2</option>
</select>    

<input name="number" type="text"  id="number">

<select name="price" id="price">
    <option id="price1">$5</option>
    <option id="price2">%10</option>
</select>    

<button type="button" data-loading-text="enviando..." onclick="submitInfo()">Send</button>

Next add the url path for the action you added.
urls.py:

from django.urls import path
from . import views

app_name = "main"   

urlpatterns = [
    ...
    path("external", views.external_api_view, name="home")

]

Then get the input values in views.py

import requests
import time
from rest_framework import status
from rest_framework.response import Response

def external_api_view(request):
    if request.method == "POST":
        attempt_num = 0  # keep track of how many times we've retried
        while attempt_num < MAX_RETRIES:
            url = 'www.apiexternal.com/endpoint'
            payload = {'Token':'My_Secret_Token','product':request.POST.get("options"),'price':request.POST.get("price")}
            r = requests.post(url, data = payload)
            if r.status_code == 200:
                data = r.json()
                return Response(data, status=status.HTTP_200_OK)
            else:
                attempt_num += 1
                # You can probably use a logger to log the error here
                time.sleep(5)  # Wait for 5 seconds before re-trying
        return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)

Leave a comment