TypeError:get()缺少1个必需的位置参数:'id'

时间:2019-12-30 06:42:45

标签: regex django rest mixins serializer

TypeError:get()缺少1个必需的位置参数:'id' 在url.py中,我无法提及id对象。我在ur_pattern中提供的正则表达式,浏览器无法找到“ id”。

url.py

from django.contrib import admin
from django.urls import path
from withoutrest import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^api/(?P<id>\d+)$', views.EmployeeDetails.as_view()),
]

view.py

from django.shortcuts import render
from django.views.generic import View
from withoutrest.models import employee
from django.http import HttpResponse
import json
from django.core.serializers import serialize
from withoutrest.mixins import serializeMixin

# Create your views here.
class EmployeeDetails(serializeMixin,View):
    def get(self, request, id, *args, **kwargs):
        emp = employee.objects.get(id=id)
        json_data = self.serialize([emp,])
        return HttpResponse(json_data, content_type='application/json')

mixins.py

from django.core.serializers import serialize
import json
class serializeMixin(object):
    def serialize(self, emp):
        json_data= serialize('json', emp)
        pdict= json.loads(json_data)
        list=[]
        for obj in pdict:
            emp_data=obj['fields']
            list.append(emp_data)
        json_data=json.dumps(list)
        return json_data

test.py

import requests

BASE_URL = 'http://127.0.0.1:8000/'
ENDPOINT = 'api/'


def get_resource(id):
    resp = requests.get(BASE_URL + ENDPOINT + id + '/')
    print(resp.status_code)
    print(resp.json())
get_resource(id)

2 个答案:

答案 0 :(得分:0)

# Change your urls.py and import re_path

from django.urls import path, re_path
from withoutrest import views

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^api/(?P<id>\d+)$', views.EmployeeDetails.as_view()),
]

答案 1 :(得分:0)

使用re_path代替路径。

类似这样的东西:

re_path(r'^api/(?P<id>\d+)/$', views.EmployeeDetails.as_view()),