I need to submit a form to an API and I want to pass the form fields value to the Payload for a python request API,enter code here how can I achieve this?
models.py
class Book(models.Model):
trading_name = models.CharField(max_length=100, null=True)
industry = models.CharField(max_length=100, null=True)
vat = models.CharField(max_length=100, null=True)
address_street = models.CharField(max_length=100, null=True)
address_city = models.CharField(max_length=100, null=True)
address_postal_code = models.CharField(max_length=100, null=True)
address_iso_country = CountryField(max_length=100, null=True)
def __str__(self):
return self.title
forms.py
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ('trading_name', 'industry', 'vat', 'address_street',
'address_city', 'address_postal_code', 'address_iso_country')
views.py
def upload_kyb(request):
if request.method == 'POST':
url = 'https://stoplight.io/mocks/railsbank/api/25652867/v1/customer/endusers'
headers = {
'Content-Type': "application/json",
'Accept': "application/json",
'Authorization': ""
}
payload = "{ \n \"company\": {\n \"name\": \"Example Company\", \n \"trading_name\": \"jiuliasu\",\n \"industry\": \"Telecommunications\",\n \"vat\": \"GB123456789\",\n \"registration_address\": \n {\n \"address_refinement\": \"Floor 15\", \n \"address_number\": \"20\", \n \"address_street\": \"Floor 15\", \n \"address_city\": \"London\", \n \"address_postal_code\": \"SS8 9JH\", \n \"address_iso_country\": \"GBR\" \n }\n\t}\n}"
response = requests.request("POST", url, data=json.dumps(payload), headers=headers)
print(response.text)
print(payload)
# form = Kybform(request.POST, request.FILES)
form = BookForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('kyb_list')
else:
form = BookForm()
return render(request, 'kybstart/upload_kyb.html', {
'form': form
})
I can get the response in the console but how can I actually pass the form inputs dynamically into the Payload?
CodePudding user response:
Assign variables to the items in your post then use the variables in your payload
You can break up the string with quotes and concatenate the variables.
Example Payload = "Trading name: " name_variable " industry"
CodePudding user response:
sorted using f-string for the payload:
payload = f'{{ "company": {nl}, "name": {trading_name}, {nl}"industry": {industry}, {nl}"vat": {vat}, {nl}, "registration_address": {nl}, "address_number": {address_street}, {nl}"address_street": {address_city}}}'
and assign variable as per the answer above
trading_name = request.POST.get('trading_name')
nl = '\n'
industry = request.POST.get('industry')
vat = request.POST.get('vat')
address_street = request.POST.get('address_street')
address_city = request.POST.get('address_city')