当前位置:  开发笔记 > 编程语言 > 正文

ViewDoesNotExist即使它确实存在

如何解决《ViewDoesNotExist即使它确实存在》经验,为你挑选了1个好方法。

这就是事情.我的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):



1> karthikr..:

将您更改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):


class SnippetSerializer(serializers.Serializer):类SnippetSerializer(serializers.ModelSerializer):为我解决了这个问题.
推荐阅读
赛亚兔备_393
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有