DJANGO - 'str'对象没有属性'数据'

时间:2017-02-21 13:15:22

标签: python json django django-rest-framework

我正在使用Django和DRF做一个项目。我有一个视图,列出项目的详细信息(Conta)。并且所有字段都是可编辑的,因此用户可以编辑该对象。问题是得到错误:'str'对象没有属性'data'

代码:

class ContaDetailsHTML(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'conta_details.html'

    def get(self, request, pk):
        user = request.user
        conta = get_object_or_404(Conta, pk=pk,user=user)
        serializer = ContaDetailsSerializerHTML(conta)
        return Response({'serializer': serializer, 'conta': conta})

    def post(self, request, pk):
        user = request.user
        conta = get_object_or_404(Conta, pk=pk, user=user)
        serializer = ContaDetailsSerializerPosts(conta, data=request.data)
        if not serializer.is_valid():
            return Response({'serializer': serializer, 'conta': conta})
        serializer.save()
        return Response(status=status.HTTP_200_OK)

在模板中:

{% load rest_framework %}

<html><body>

<h1>Conta - {{ conta.nome }}</h1>

<form action="{% url 'conta_details' pk=2 %}" method="POST">
    {% csrf_token %}
    {% render_form serializer %}
    <input type="submit" value="Save">
</form>

</body></html>

pk = 2仅用于测试目的。

当我编辑字段并按“保存”时,会弹出该错误。有什么想法吗?

编辑,网址:

url(r'^api/contas/(?P<pk>[0-9]+)/$', views.ContaDetailsHTML.as_view(), name='conta_details'),

编辑,错误追溯

Environment:


Request Method: POST
Request URL: http://localhost:8000/project/api/contas/2/

Django Version: 1.10.5
Python Version: 3.6.0
Installed Applications:
['project.apps.ProjectConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template C:\Documentos\Mestrado\ISCN\django\PF\project\templates\conta_details.html, error at line 9
   'str' object has no attribute 'data'   1 : {% load rest_framework %}
   2 : 
   3 : <html><body>
   4 : 
   5 : <h1>Conta - {{ conta.nome }}</h1>
   6 : 
   7 : <form action="{% url 'conta_details' pk=2 %}" method="POST">
   8 :     {% csrf_token %}
   9 :      {% render_form serializer %} 
   10 :     <input type="submit" value="Save">
   11 : </form>
   12 : 
   13 : </body></html>

Traceback:

File "C:\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
  39.             response = get_response(request)

File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  215.                 response = response.render()

File "C:\Python36-32\lib\site-packages\django\template\response.py" in render
  109.             self.content = self.rendered_content

File "C:\Python36-32\lib\site-packages\rest_framework\response.py" in rendered_content
  72.         ret = renderer.render(self.data, accepted_media_type, context)

File "C:\Python36-32\lib\site-packages\rest_framework\renderers.py" in render
  174.         return template_render(template, context, request=request)

File "C:\Python36-32\lib\site-packages\rest_framework\compat.py" in template_render
  306.         return template.render(context, request=request)

File "C:\Python36-32\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python36-32\lib\site-packages\django\template\base.py" in render
  208.                     return self._render(context)

File "C:\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Python36-32\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Python36-32\lib\site-packages\django\template\library.py" in render
  203.         output = self.func(*resolved_args, **resolved_kwargs)

File "C:\Python36-32\lib\site-packages\rest_framework\templatetags\rest_framework.py" in render_form
  31.     return renderer.render(serializer.data, None, {'style': style})

Exception Type: AttributeError at /project/api/contas/2/
Exception Value: 'str' object has no attribute 'data'

1 个答案:

答案 0 :(得分:1)

文件似乎很好,除了行:

conta = get_object_or_404(Conta, pk=pk, user=user)
serializer = ContaDetailsSerializerPosts(conta, data=request.data)

可能问题出在哪里,即

conta

如果您在'str' object has no attribute 'data' 中收到404(未找到)(因为您尝试发布/创建id = 2的条目,如何先查询它),以及何时传递,该怎么办?到Serializer数据结构/类型其他QuerySet,这是你可能得到的错误:

conta = get_object_or_404(Conta, pk=pk, user=user)

可能的解决方案: 摆脱界限

serializer = ContaDetailsSerializerPosts(data=request.data)

将序列化器调用为

if pk: # the update request 
    conta = get_object_or_404(Conta, pk=pk, user=user)
    serializer = ContaDetailsSerializerPosts(conta, data=request.data)
else:  # the create request
    serializer = ContaDetailsSerializerPosts(data=request.data)

如果您使用相同的视图进行创建(POST)和更新(PUT),请执行以下操作:

javax.net.ssl.trustStore