Home > Mobile >  How to make create (POST) request using api in django
How to make create (POST) request using api in django

Time:11-15

I wish to create new a data when any user was make any requests like Create Export Delete or Update but now I am working on Export.. I have two urls one is having data of tables (average_data urls) and one url which is have (audit_logs url) a data of user which will be created after when any user download an pdf format of the data .. so basically I wish to show which user on which time and which action he does it will get it on the audit_logs url

I am making request of post in data/views but getting error bad request at /audit_logs/create/

views.py

def averagePDF(request):
global fromDate
global toDate
global site
global device
global parameters
global interval
global data
headers = {
    'authorization': "Bearer X...............",
}
devices_url = "http://127.0.0.1:8000/stations/list"
devices_params = {
    'id': device
}
devices = requests.request("GET", devices_url, headers=headers, params=devices_params)
response = HttpResponse()
response['Content-Disposition'] = 'attachment; filename=Average Data.pdf'

elements = []


company_name = Paragraph(devices.json()[0]['site'], header_style)
elements.append(company_name)

report_data = Paragraph("Date: "   fromDate   " to "   toDate   " Station: "   devices.json()[0]['station'], title_style)
elements.append(report_data)

styles = getSampleStyleSheet()
styleN = styles['Normal']
styleN.wordWrap = 'CJK'

file_data = []
header = []
header.append("Timestamp")
header.append("Station")
for parameter in parameters:
    header.append(parameter)
file_data.append(header)
data2 = [[Paragraph(cell, styleN) for cell in row] for row in file_data]
width = (PAGE_WIDTH-50) / len(header)
table_header = Table(data2, colWidths=width, style=table_header_style)
elements.append(table_header)
table_data = []
for key, values in data.items():
    raw_data = []
    raw_data.append(str(key))
    raw_data.append(devices.json()[0]['station'])
    for value in values:
        raw_data.append(str(value))
    table_data.append(raw_data)
table_data2 = [[Paragraph(cell, styleN)for cell in row] for row in table_data]
tableRaw = LongTable(table_data2, colWidths=width, style=table_style)
elements.append(tableRaw)
doc.title = "Average Data"
meta_data = request.META.get('HTTP_X_FORWARDED_FOR')
if meta_data:
    ip = meta_data.split(',')[-1].strip()
else:
    ip = request.META.get('REMOTE_ADDR')
**now=datetime.datetime.now()
# date_time = now.strftime('%Y-%m-%dT%H:%M:%S.%f')
username=str(request.user)
action_type="Export"
action="Export"
ip_address=ip
audit_url="http://127.0.0.1:8000/audit_logs/create/"
audit_parms={
    "username":username,
    "action_type":action_type,
    "action":action,
    "ip_address":ip_address
    }
audit_obj=requests.post(audit_url, headers=headers, params=audit_parms)
print(audit_obj.json())**

when I am posting response its give me following response

{'username': 'abcpadmin', 'action_type': 'Export', 'action': 'Export', 'ip_address': '127.0.0.1'}

Bad Request: /audit_logs/create/ [15/Nov/2021 16:08:24] "POST /audit_logs/create/?username=abcpadmin&action_type=Export&action=Export&ip_address=127.0.0.1 HTTP/1.1" 400 160 <Response [400]> {'username': ['This field is required.'], 'action_type': ['This field is required.'], 'action': ['This field is required.'], 'ip_address': ['This field is required.']}

CodePudding user response:

You should take a look at djangorestframework https://www.django-rest-framework.org/tutorial/2-requests-and-responses/

This is the recommended way to write APIs with django.

CodePudding user response:

When you use requests for post in your case, you need pass data instead of params

It should be :

audit_obj=requests.post(audit_url, headers=headers, data=audit_parms)

Technically, when you do requests.post(url=your_url, params=your_params), the url will be like https://localhost?key=value with key value in params dictionary.

  • Related