Reputation: 747
I am trying to do a post request to a API, and save the result into one of my database table.
This is my code.
This is my model. patientId is a foreign key to the userId of MyUser table
class MyUser(AbstractUser):
userId = models.AutoField(primary_key=True)
gender = models.CharField(max_length=6, blank=True, null=True)
nric = models.CharField(max_length=9, blank=True, null=True)
birthday = models.DateField(blank=True, null=True)
birthTime = models.TimeField(blank=True, null=True)
class BookAppt(models.Model):
clinicId = models.CharField(max_length=20)
patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE)
scheduleTime = models.DateTimeField(blank=True, null=True)
ticketNo = models.CharField(max_length=5)
status = models.CharField(max_length=20)
view.py . The api url is from another django project
@csrf_exempt
def my_django_view(request):
if request.method == 'POST':
r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST)
else:
r = requests.get('http://127.0.0.1:8000/api/makeapp/', data=request.GET)
if r.status_code == 201 and request.method == 'POST':
data = r.json()
print(data)
patient = request.data['patientId']
patientId = MyUser.objects.get(id=patient)
saveget_attrs = {
"patientId": patientId,
"clinicId": data["clinicId"],
"scheduleTime": data["created"],
"ticketNo": data["ticketNo"],
"status": data["status"],
}
saving = BookAppt.objects.create(**saveget_attrs)
return HttpResponse(r.text)
elif r.status_code == 200: # GET response
return HttpResponse(r.json())
else:
return HttpResponse(r.text)
the result in the print(data)
is this.
[31/Jan/2018 10:21:42] "POST /api/makeapp/ HTTP/1.1" 201 139
{'id': 22, 'patientId': 4, 'clinicId': '1', 'date': '2018-07-10', 'time': '08:00 AM', 'created': '2018-01-31 01:21:42', 'ticketNo': 1, 'status': 'Booked'}
But the error is here
File "C:\Django project\AppImmuneMe2\customuser\views.py", line 31, in my_django_view
patient = request.data['patientId']
AttributeError: 'WSGIRequest' object has no attribute 'data'
Upvotes: 12
Views: 40457
Reputation: 157
Django rest framework has own Request
object, You need to use the api_view
decorator to enable this request type inside function view,
Just write before function @api(['GET' as an example])
Upvotes: 0
Reputation: 51
Change this line
patient = request.data['patientId']
for this line:
patient = request.POST['patientId']
Upvotes: 5
Reputation: 27543
well if you are printing the data
and you can see the patientId
inside it, why are you trying to use request
for that?
it can be done like this
data = r.json()
print(data)
patient = data['patientId']
patientId = MyUser.objects.get(id=patient)
Upvotes: 1
Reputation: 47374
Django rest framework has own Request object. You need to use api_view decorator to enable this request type inside function view.
Upvotes: 22