Jin*_*ama 1 django django-rest-framework
我正在尝试对API发布请求,并将结果保存到我的数据库表之一.
这是我的代码.
这是我的模特.patientId是MyUser表的userId的外键
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)
Run Code Online (Sandbox Code Playgroud)
view.py.api url来自另一个django项目
@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)
Run Code Online (Sandbox Code Playgroud)
结果print(data)就是这个.
[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'}
但错误就在这里
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'
好吧,如果你正在打印data并且你可以看到patientId它的内部,那么你为什么要尝试使用request它呢?
可以这样做
data = r.json()
print(data)
patient = data['patientId']
patientId = MyUser.objects.get(id=patient)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7505 次 |
| 最近记录: |