Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 'WSGIRequest' object has no attribute 'data'

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'

like image 827
Jin Nii Sama Avatar asked Jan 31 '18 04:01

Jin Nii Sama


1 Answers

Django rest framework has own Request object. You need to use api_view decorator to enable this request type inside function view.

like image 123
neverwalkaloner Avatar answered Sep 27 '22 21:09

neverwalkaloner