1

事情就是这样。我的 urls.py :

urlpatterns = patterns('snippets.views',
                       url(r'^snippets/$', 'snippet_list'),
                       url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'),
                       )

我的意见.py:

class JSONResponse(HttpResponse):

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

    @csrf_exempt
    def snippet_list(request):
        if request.method == 'GET':
            snippets = Snippet.objects.all()
            serializer = SnippetSerializer(snippets, many=True)
            return JSONResponse(serializer.data)

        elif request.method == 'POST':
            data = JSONParser().parse(request)
            serializer = SnippetSerializer(data=data)
            if serializer.is_valid():
                serializer.save()
                return JSONResponse(serializer.data, status=201)
            else:
                return JSONResponse(serializer.errors, status=400)

我正在关注教程。

当我在 local/snippets/ 时出现此错误:

/snippets/ 处的 ViewDoesNotExist 无法导入 snippets.views.snippet_list。模块片段.views 中不存在视图。

更新:解决此问题后我拥有的 ErrorKey:

KeyError at /snippets/
'id'

Environment:

Request Method: GET
Request URL: http://localhost:8000/snippets/

Django Version: 1.5.1
Python Version: 2.7.4
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'snippets')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/home/thomas/.virtualenvs/REST/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/thomas/.virtualenvs/REST/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  77.         return view_func(*args, **kwargs)
File "/home/thomas/projets/rest/snippets/views.py" in snippet_list
  21.         serializer = SnippetSerializer(snippets, many=True)
File "/home/thomas/.virtualenvs/REST/local/lib/python2.7/site-packages/rest_framework/serializers.py" in __init__
  159.         self.fields = self.get_fields()
File "/home/thomas/.virtualenvs/REST/local/lib/python2.7/site-packages/rest_framework/serializers.py" in get_fields
  206.                 new[key] = ret[key]

Exception Type: KeyError at /snippets/
Exception Value: 'id'

更新 SnippetSerializer 类:

class SnippetSerializer(serializers.Serializer):

    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance, given a dictionnary
        or deserialized field values

        Note that if we don't define this method, then deserializing
        data will simply return a dictionnary of items.
        """

        if instance:
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        return Snippet(**attrs)
4

2 回答 2

8

将您更改views.py为:

class JSONResponse(HttpResponse):

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def snippet_list(request, pk=None):
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        else:
            return JSONResponse(serializer.errors, status=400)

此外,您需要pk作为视图的参数才能正常工作。

您需要更改class SnippetSerializer(serializers.Serializer):class SnippetSerializer(serializers.ModelSerializer):

于 2013-05-24T13:37:03.070 回答
2

取消你的def snippet_list(request):块,它会更好地工作。

您的请求不在模块的全局范围内。所以找不到。

于 2013-05-24T13:32:26.943 回答