我正在尝试更新我的数据库的对象(但只有一个字段),问题是,当我尝试进行更新时,我得到一个错误,指出不允许使用PUT方法。
这是我的观点:
class DeviceViewSet(viewsets.ModelViewSet):
"""
Show, create and filter devices.
"""
queryset = Device.objects.all()
serializer_class = DeviceSerializer
def list(self, request, *args, **kwargs):
devices = Device.objects.filter(user=request.user.pk, role='E')
serializer = DeviceSerializer(devices, many=True)
return Response(serializer.data)
def create(self, request, *args, **kwargs):
data = {
'registration_id': request.data['regId'], 'user': request.user.pk, 'device_id': request.data['imei'],
'type': 'android', 'label': request.data['label'], 'role': request.data['role']
}
serializer = DeviceSerializer(data=data)
if serializer.is_valid():
serializer.save()
device = Device.objects.filter(device_id=request.data['imei'])
device.send_message("Enhorabuena!", "El dispositivo se ha registrado correctamente.")
return Response(serializer.data)
return Response(serializer.errors)
def update(self, request, *args, **kwargs):
device = Device.objects.filter(device_id=request.data['imei'])
device.registration_id = request.data['regId']
device.save()
serializer = DeviceSerializer(device)
return Response({'ok': 'oks'})
我的序列化器:
class DeviceSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=False)
class Meta:
model = Device
fields = '__all__'
我的网址:
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from decaught import views
urlpatterns = [
url(r'^devices/$', views.DeviceViewSet),
]
urlpatterns = format_suffix_patterns(urlpatterns)
我正在使用Postman发送PUT请求:
知道出了什么问题吗?
答案 0 :(得分:1)
PUT
设置时,资源标识符应位于URL(pk)中。 PUT请求是幂等。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT
在DRF文档中,将pk作为参数传递给更新方法
def update(self, request, pk=None):
pass
http://www.django-rest-framework.org/api-guide/viewsets/#viewset-actions
代替传递它作为key:value对并通过request.data
PUT调用来访问它应该像
localhost:8000/devices/<PK-HERE>/
(对不起,英语不好)
答案 1 :(得分:0)
错误在我们的网址中。您需要选择一些device
到PUT信息。试试localhost:8000/devices/1/
。我假设您的API通过pk