0

I am using django and python request to make a post request to this endpoint with the authorization header and body gotten from this website. i want your assist to get this difficulty proper and to make this code work.

class RechargeData(models.Model, Main):
     user = models.ForeignKey(User, default=1,on_delete=models.CASCADE)
     phone_number = models.CharField(validators=[Main.phone_regex], max_length=10) 
     network = models.CharField(choices=Main.OPERATORS, max_length=15)
     plan = models.IntegerField(choices=Main.PLANS)
     amount = models.DecimalField(max_digits=10, decimal_places=2) 

i have the view.py file that contains the python request as follows

import requests import json from .forms import RechargeForm

def rechargedata(request):
  url = "http://127.0.0.1:8000/api/data/"
  payload = "{\"network\": network_id,\n\"mobile_number\": \"09037346247\",\n\"plan\": plan_id}" 
  headers = {'Authorization': 'Token 5fd60vcdfddfxddsssfddff9a0a8742d','Content-Type': 'application/json'}

  response = requests.request("POST", url, headers=headers, data=payload)

  if request.method == "POST":
      form = RechargeForm(request.POST)
      if form.is_valid():
          phone_number = form.cleaned_data['phone_number']
          network = form.cleaned_data['network']
          amount = form.cleaned_data['amount']
          plan = form.cleaned_data['plan']
      form.save

      context = RequestContext(request, {
          'phone_number': response.data.mobile_number,
          'network': response.data.network_id, 
          'mobile_number': response.data.network_id,
          'plan': response.data.plan_id,
          })
      return render(request, 'embeds.html', {'context': context, 'form'; form})
   else:
        form = RechargeForm()

   return render(request, 'index.html', { context, 'form': form})

This code is not working and am sure not to be getting something proper here.

can someone help me out?

  • Hard to say why, but a few things jump out at first glance: your 'form.save()' should be indented one tab to the right (so as to be under the '_is_valid()' block. You're missing a period in 'responsedata.mobile_number'. Your context is being rendered as a value within a dictionary, instead of being the dictionary itself. I.e., instead of {'context':context} you would normally just have: context. Hope that makes some sense. – Milo Persic Feb 26 '22 at 01:29
  • @sc_props sir, am i right by calling the request by doing response.data.mobile_number inside context dic? or do i need to extract json data by doing data = response.json()? Calling request data to my model object is where am not getting right. Thanks for the earlier correction and thanks for coming for my rescue – Strong Imade Feb 26 '22 at 05:33
  • Have you tried "response = requests.post(url..." etc? Maybe this answer can help: https://stackoverflow.com/questions/15900338/python-request-post-with-param-data – Milo Persic Feb 26 '22 at 13:20

0 Answers0