当我尝试在Django的数据库中保存帖子时出现此错误。
我在做什么错,我该如何解决?
在/ account / create-post处的AttributeError
'str'对象没有属性'data'
我有这个字段
我的模特:
class Post(models.Model):
created_date = models.DateTimeField()
title = models.CharField(max_length=100)
profile_image = models.ImageField(upload_to='poze', blank=True, null=True)
text = models.CharField(max_length=1000, default='Nimic', blank=True)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
查看:
class CreatePost(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'create_post.html'
def get(self,request):
serializer=CreatePostSerializer()
return Response({'fields':serializer})
def post(self, request):
serializer = CreatePostSerializer(data=request.data)
if not serializer.is_valid():
return Response({'serializer': serializer.data})
user = UserProfile.objects.filter(username=request.user.username).first()
serializer.save(user=user)
return redirect('mainPage')
Create_post.html:
{% extends 'base.html' %}
{% load rest_framework %}
{% block content %}
<div class="offset-3 col-md-6">
<form action="{% url 'create_post' %}" method="POST">
<div class="form-group">
{% csrf_token %}
{% render_form fields %}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}
URL:
url(r'create-post$', login_required(CreatePost.as_view()), name='create_post'),
控制台中的内容:
Internal Server Error: /account/create-post Traceback (most recent call last): File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 158, in _get_response
response = self.process_exception_by_middleware(e, request) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 156, in _get_response
response = response.render() File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\response.py", line 106, in render
self.content = self.rendered_content File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\renderers.py", line 176, in render
return template.render(context, request=request) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 175, in render
return self._render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 943, in render
bit = node.render_annotated(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 910, in render_annotated
return self.render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader_tags.py", line 155, in render
return compiled_parent._render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 943, in render
bit = node.render_annotated(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 910, in render_annotated
return self.render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader_tags.py", line 67, in render
result = block.nodelist.render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 943, in render
bit = node.render_annotated(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 910, in render_annotated
return self.render(context) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\library.py", line 192, in render
output = self.func(*resolved_args, **resolved_kwargs) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\templatetags\rest_framework.py", line 84, in render_form
return renderer.render(serializer.data, None, {'style': style}) AttributeError: 'str' object has no attribute 'data' [10/Aug/2018 17:51:09] "POST /account/create-post HTTP/1.1" 500 147258
答案 0 :(得分:0)
问题似乎出在View
中的函数中:
def post(self, request):
serializer = CreatePostSerializer(data=request.data) <---- ERROR
if not serializer.is_valid():
return Response({'serializer': serializer.data})
request
参数的类型为str
,不是对象,因此,在尝试访问{{1}的不存在的AttributeError
属性时,data
}。我对Django并不完全熟悉,但是根据我对HTTP请求和客户端服务器“材料”的一些了解,我假设str
作为字符串传递,并且需要解析并转换为对象。
答案 1 :(得分:0)
Django rest框架会寻找render_form模板标签,以渲染Serializer。
可以使用render_form模板标签将序列化器呈现为表单,并包括序列化器实例作为模板的上下文。
https://www.django-rest-framework.org/topics/html-and-forms/
自此,您将其命名为fields
。发布后应该是
return Response({'fields':serializer})
所以
class CreatePost(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'Create_post.html'
def get(self,request):
serializer=serializers.CreatePOSTS()
return Response({'fields':serializer})
def post(self, request):
serializer = serializers.CreatePOSTS(data=request.data)
if not serializer.is_valid():
return Response({'fields':serializer}) #forms + serializer errors. :)
user = customers.objects.filter(username=request.user.username).first()
serializer.save(user=user)
return redirect('mainPage')
希望这会有所帮助:)
答案 2 :(得分:0)
在您的 views.py 中尝试一下:
class CreatePost(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'create_post.html'
def get(self,request):
serializer=CreatePostSerializer
return Response({'serializer':serializer})
def post(self, request):
serializer = CreatePostSerializer(data=request.data)
if not serializer.is_valid():
return Response({'serializer': serializer})
user = UserProfile.objects.filter(username=request.user.username).first()
serializer.save(user=user)
return redirect('mainPage')
在您的 create_post.html 使用中:
{% extends 'base.html' %}
{% load rest_framework %}
{% block content %}
<div class="offset-3 col-md-6">
<form action="{% url 'create_post' %}" method="POST">
<div class="form-group">
{% csrf_token %}
{% render_form serializer %}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}
希望有帮助。