这就是事情.我的urls.py:
urlpatterns = patterns('snippets.views', url(r'^snippets/$', 'snippet_list'), url(r'^snippets/(?P[0-9]+)/$', 'snippet_detail'), )
我的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): 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.模块snippets.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)
karthikr.. 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):
将您更改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):