我在Django中执行JSONRenderer.render(serialized_student_data.data)时遇到问题

whhtz7ly  于 2023-02-17  发布在  Go
关注(0)|答案(2)|浏览(93)
  • 我是Django新手,每当我执行json_data = JSONRenderer.render(serialized_student_data.data)这行代码时,它会给我类似TypeError的错误:render()缺少1个必需的位置参数:'数据'*
    #以下是www.example.com中的代码models.py
class StudentModel(models.Model):
    name = models.CharField(max_length=100, default='user')
    roll_no = models.IntegerField(default=1)
    city = models.CharField(max_length=100, default='Ahmedabad')

#以下是www.example.com中的代码serializers.py

class StudentSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    roll_no = serializers.IntegerField()
    city = serializers.CharField(max_length=100)

#以下是www.example.com中的代码views.py

def student_view(request):
    student_object = StudentModel.objects.get(id=3)
    serialized_student_data = StudentSerializer(student_object)
    json_data = JSONRenderer.render(serialized_student_data.data)
    return HttpResponse(json_data, content_type='application/json')
vlf7wbxs

vlf7wbxs1#

应该创建JSONRender对象而不是use类,代码将是,

json_data = JSONRenderer().render(data=serialized_student_data.data)
n9vozmp4

n9vozmp42#

create a separate render file in the same app you are working on.
code of a renderer will  work for all the views you are using add the 
renderer class where you want to use 

from rest_framework import renderers
import json

class StudentRenderer(renderers.JSONRenderer):
  charset='utf-8'
  def render(self, data, accepted_media_type=None, renderer_context=None):
    response = ''
    if 'ErrorDetail' in str(data):
      response = json.dumps({'errors':data})
    else:
      response = json.dumps(data)
    
    return response

then add the render class into the student view class 

first import the respective library.
from user.renderers import StudentRenderer

use this in the student view anywhere 
renderer_classes = [StudentRenderer]

相关问题