【问题标题】:django-rest-framwork: AttributeError, 'Response' object has no attribute 'title'django-rest-framework:AttributeError,“响应”对象没有属性“标题”
【发布时间】:2021-06-28 04:30:17
【问题描述】:

AttributeError: 尝试在序列化程序 QuestionSerializer 上获取字段 title 的值时出现 AttributeError。 序列化程序字段可能命名不正确,并且与 Response 实例上的任何属性或键都不匹配。 原始异常文本是:“响应”对象没有属性“标题”。

models.py

class Question(models.Model):
    title = models.TextField(null=False,blank=False)
    status = models.CharField(default='inactive',max_length=10)
    created_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ('id',)

urls.py

urlpatterns = [
    path('poll/<int:id>/', PollDetailsAPIView.as_view()),
]

serializers.py

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields =[
            'id',
            'title',
            'status',
            'created_by'
        ]

views.py

class PollDetailsAPIView(APIView):
    
    def get_object(self, id):
        try:
            return Question.objects.get(id=id)
        except Question.DoesNotExist:
            return Response({"error": "Question does not exist"}, status=status.HTTP_404_NOT_FOUND)
    
    def get(self, request, id):
        question = self.get_object(id)
        serializer = QuestionSerializer(question)
        return Response(serializer.data)

关于邮递员,我正在尝试获取一个不存在的 ID,但我没有收到此回复 "error": "Question does not exist"Error: 404,而是不断收到 error 500 Internal server error

【问题讨论】:

    标签: python django


    【解决方案1】:

    当您尝试获取不存在的对象时,您的get_object 方法会返回一个Response,然后将其传递给序列化程序。由于它不能序列化Response,它会引发AttributeError。您应该做的是在except 中引发Http404 错误:

    def get_object(self, id):
        try:
            return Question.objects.get(id=id)
        except Question.DoesNotExist:
            raise Http404('Not found')
    

    或使用 django 快捷方式get_object_or_404:

    from django.shortcuts import get_object_or_404
    
    
    class PollDetailsAPIView(APIView):
        def get(self, request, id):
            question = get_object_or_404(Question, id=id)
            serializer = QuestionSerializer(question)
            return Response(serializer.data)
    

    【讨论】:

    • 问题是它正在使用基于函数的视图,但是当我尝试切换到基于类的视图时,我一直收到这个错误。
    • 另外,如果我关注 Http404,我如何自定义消息,因为 " " 中的任何文本都不起作用?
    • @kd12345 试试this
    • 我没有使用任何模板,我想更改出现在 json 对象中的消息,目前我得到了这个{"detail": "Not found."}
    • 啊,对不起,我的错。那你可以试试from rest_framework.exceptions import NotFound,把Http404提高起来:raise NotFound('&lt;Custom message&gt;')
    猜你喜欢
    • 1970-01-01
    • 2018-08-14
    • 2015-10-15
    • 2019-04-30
    • 2018-11-05
    • 2017-03-04
    • 1970-01-01
    • 2021-05-02
    • 2018-09-13
    相关资源
    最近更新 更多