PUT方法不被允许

2024-05-23 14:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Django REST框架创建可编辑的数据表。我尝试使用PUT方法更改表字段,但我得到:

Method Not Allowed (PUT): /api/zaposleni/2/

Method Not Allowed: /api/zaposleni/2/

我在stackoverflow上检查过类似的问题。我返回了URL和请求体中的键,并且PUT方法被修饰了,这应该不会触发我得到的错误。 添加断点似乎表明代码执行甚至没有到达我的视图。在

class ZaposleniDetail(viewsets.ViewSet):
    @action(detail=True, methods=['put'])
    def put(self, request, pk):

        try:
            zaposleni = Zaposleni.objects.get(pk=pk)
        except Zaposleni.DoesNotExist:
            return HttpResponse(status=404)

        if request.method == 'PUT':
            # this is when you make changes with datatables editor. I think there was a reason I used PUT instead of POST
            # but I cant remember why that was right now.
            # change pk to an int
            pk = int(pk)

            # parse request querydict into dict
            # I could not find a better way to do this.
            data = parser.parse(request.body)

            # extract out the nested dict needed for drf post
            # datatables always send it nested in 'data' but you can change that if you want to
            parsed_data = data['data'][pk]

            for key, val in parsed_data.items():
                # this is the ugliest part of the function
                # This looks at every value in the dictionary and if it is an empty string then it skips it.
                # An empty string means there wasn't a change
                # If it has data if will go through the keys until it gets a match and then update that in the database
                # The problem is I don't want it to update everything because if there was no change it will send a blank string
                # and then it could overwrite an existing value in the database with a blank string.
                if key in parsed_data:
                    if val == '':
                        continue
                    else:
                        if key == 'ima_prezime':
                            Zaposleni.objects.filter(pk=pk).update(ima_prezime=val)
                        if key == 'datum':
                            Zaposleni.objects.filter(pk=pk).update(
                                datum=val)
                        if key == 'boolean':
                            Zaposleni.objects.filter(pk=pk).update(boolean=val)

            # After making a change in the database you will need to send the data back to datatables
            # If it doesn't match what datatables sends then it will not refresh the datatable
            # this code formats everything to match what datatables send in the PUT request
            parsed_data['id'] = str(pk)

            serializer = ZaposleniSerializer(
                Zaposleni.objects.filter(pk=pk), many=True)
            data = serializer.data

            # This will nest it back into the 'data' dict
            data_dict = {'data': data}
            json_data = json.dumps(data_dict)

            return HttpResponse(json_data)

网址:

^{pr2}$

jquery:

$(document).ready(function () {
    editor = new $.fn.dataTable.Editor({
        ajax: {
            url: 'api/zaposleni/_id_/',
            type: 'PUT',
            headers: {'X-CSRFToken': '{{ csrf_token }}'},
        },
        "table": "#example",
        "idSrc": 'id',
        "fields": [    
            {
                "label": "Ime Prezime",
                "name": "ima_prezime",
            },
            {
                "label": "Datum",
                "name": "datum",
                "type": "date",
            },
            {
                "label": "Boolean",
                "name": "boolean",
                "type": "select",
                options: [
                    {label: "", value: ""},
                    {label: "True", value: "True"},
                    {label: "False", value: "False"}
                ]
            },
        ]
    });
});

Tags: thetoindataifobjectsputrequest
1条回答
网友
1楼 · 发布于 2024-05-23 14:15:54

这是因为查询正在访问另一个视图(TemplateView),该视图显然不接受PUT方法。Django正在尝试从上到下匹配URL,以及您的第二个URL regex:

url(r'^', views.TemplateView.as_view(template_name="zaposleni.html"))

正在匹配/api/zaposleni/2/。这是因为没有$和regex的结尾。在

它应该是:

^{pr2}$

相关问题 更多 >