TypeError repr(o)+"不是JSON可序列化的#34;

时间:2018-04-18 11:02:31

标签: python django django-rest-framework django-serializer

这是我第一次使用休息框架。我正在尝试序列化我的家庭应用。

档案 models.py

class User(AbstractUser):
    """User model."""

    username = None
    email = models.EmailField(_('email address'), unique=True)
    location = map_fields.AddressField(max_length=200)
    preferred = models.ManyToManyField(Place, related_name='Preferred')
    disliked = models.ManyToManyField(Place, related_name='Disliked')
    maplocation = gis_models.PointField("longitude/latitude", geography=True, blank=False, null=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    @classmethod
    def make_preferred(cls, current_email, new_pref_place):
        user, created = cls.objects.get_or_create(
            email=current_email
        )
        user.preferred.add(new_pref_place)

    @classmethod
    def remove_preferred(cls, current_email, pref_place):
        user, created = cls.objects.get_or_create(
            email=current_email
        )
        user.preferred.remove(pref_)lace

    @classmethod
    def make_dislike(cls, current_email, dislike_place):
        user, created = cls.objects.get_or_create(
            email=current_email
        )
        user.disliked.add(dislike_place)

    @classmethod
    def remove_dislike(cls, current_email, dislike_place):
        user, created = cls.objects.get_or_create(
            email=current_email
        )
        user.disliked.remove(dislike_place)

class Place(models.Model):
    name = models.CharField(max_length=200)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular place across whole library")
    email = models.EmailField(max_length=70,blank=False)
    city = models.CharField('city', blank=False, default='Rabat', max_length=200, null=False)
    place_pic = models.ImageField(upload_to = 'pic_folder/', default = 'http://placehold.it/150x150', null= True)
    location = gis_models.PointField("longitude/latitude", geography=True, blank=False, null=True)
    #objects = gis_models.GeoManager()

    def __unicode__(self):
        return self.name, 'location'

文件 views.py

@login_required
@api_view(['GET', 'PUT', 'DELETE'])
def home(request, format=None):
"""
    View function for home page of site.
"""
place_list = Place.objects.all() # get all the places from db to place_list
user = User.objects.get(email=request.user) # get the email of the current user
preferred_list = user.preferred.all() #get all the preferred places for the current user
disliked_list = user.disliked.all() #get all the disliked places for the current user in disliked_list
ref_location = user.maplocation # get the coordinates of the user from maplocation to ref_location
place_order = Place.objects.annotate(distance=D('location', ref_location)).order_by('distance')     # Render the HTML template home.html with the data in the context variable
return Response({'place_list': PlaceSerializer(place_list,many=True).data}, {'place_order': PlaceSerializer(place_order,many=True).data}, {'disliked_list': PlaceSerializer(disliked_list,many=True).data}, {'preferred_list': PlaceSerializer(preferred_list,many=True).data},)


@login_required
@api_view(['GET', 'PUT', 'DELETE'])
def favorites(request, format=None):
"""
    View of the preferred plac list
"""
user = User.objects.get(email=request.user)
preferred_list = user.preferred.all()
return Response({'preferred_list': PlaceSerializer(preferred_list,many=True).data},
)

@login_required
@api_view(['GET', 'PUT', 'DELETE'])
def dislikes(request, format=None):
"""
    View of the disliked place list
"""
user = User.objects.get(email=request.user)
disliked_list = user.disliked.all()
return Response({'disliked_list': PlaceSerializer(disliked_list,many=True).data},
)


@api_view(['GET', 'PUT', 'DELETE'])
def change_preferred(request, operation, id):
"""
    add or remove place from preferred list of places
"""
place = Place.objects.get(id=id)
if operation == 'add':
    User.make_preferred(request.user, place)
    return redirect('home')
elif operation == 'remove':
    User.remove_preferred(request.user, place)
    return redirect('favorites')

@api_view(['GET', 'PUT', 'DELETE'])
def change_disliked(request, operation, id):
"""
add or remove place from disliked list of places
"""
place = Plac.objects.get(id=id)
if operation == 'add':
    User.make_dislike(request.user, place)
    return redirect('home')
elif operation == 'remove':
    User.remove_dislike(request.user, place)
    return redirect('home')


@api_view(['GET', 'POST'])
def signup(request):
  if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
        form.save()
        email = form.cleaned_data.get('email')
        raw_password = form.cleaned_data.get('password1')
        user = authenticate(email=email, password=raw_password)
        login(request, user)
        return redirect('/city_places')
else:
    form = SignUpForm()
return Response(request, 'signup.html', {'form': UserSerializer(form,many=True).data})

文件 serializers.py

from rest_framework import serializers
from .models import Shop, User
from rest_framework_gis.serializers import GeoFeatureModelSerializer
from .views import *

class ShopSerializer(serializers.ModelSerializer):
    geo_field = "location"
    class Meta:
        model = Shop
        fields = ('location' ,'name', 'shop_pic')


 class UserSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(format='hex_verbose')
    geo_field = "maplocation"
    class Meta:
        model = User
        fields =  '__all__'

我在城市中有一些地方,想要将它们显示给用户,我会查询按距离排序并在主页中显示它们,当我尝试序列化时,我得到了这个错误:

Internal Server Error: /api/
Traceback (most recent call last):
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/handlers/base.py", line 158, in _get_response
response = self.process_exception_by_middleware(e, request)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/handlers/base.py", line 156, in _get_response
response = response.render()
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/template/response.py", line 106, in render
self.content = self.rendered_content
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/renderers.py", line 105, in render
allow_nan=not self.strict, separators=separators
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/utils/json.py", line 28, in dumps
return json.dumps(*args, **kwargs)
File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/utils/encoders.py", line 68, in default
return super(JSONEncoder, self).default(obj)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Place: Place object (3773482c-862d-4cc3-b2dd-8967e00cd730)> is not JSON serializable
[18/Apr/2018 11:49:11] "GET /api/?format=json HTTP/1.1" 500 129970

我不知道这是否是最好的方法,但是我试图获得最喜欢的地方和一些黑名单。

编辑问题 使用@Jerin Peter George后我得到关于http状态代码必须是整数的错误

Internal Server Error: /api/
Traceback (most recent call last):
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/http/response.py", line 49, in __init__
self.status_code = int(status)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "~/Projects/Places/city_Place/views.py", line 38, in home
return Response({'place_list': PlaceSerializer(place_list,many=True).data}, {'place_order': PlaceSerializer(place_order,many=True).data}, {'disliked_list': PlaceSerializer(disliked_list,many=True).data}, {'preferred_list': PlaceSerializer(preferred_list,many=True).data},)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/rest_framework/response.py", line 32, in __init__
super(Response, self).__init__(None, status=status)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/template/response.py", line 36, in __init__
super().__init__('', content_type, status, charset=charset)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/http/response.py", line 283, in __init__
super().__init__(*args, **kwargs)
File "~/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/http/response.py", line 51, in __init__
raise TypeError('HTTP status code must be an integer.')
TypeError: HTTP status code must be an integer.
[19/Apr/2018 04:05:36] "GET /api/ HTTP/1.1" 500 168031

1 个答案:

答案 0 :(得分:0)

导致异常的home()中的这一行,

return Response({'place_list': place_list,
                 'preferred_list': preferred_list,
                 'disliked_list': disliked_list,
                 'place_order': place_order, })


在此语句中,您将Place实例/查询集传递给响应,而不是JSON Serializable。所以你需要做的是,在返回之前序列化queryset

示例
将以上声明替换为以下,

return Response({'place_list': PlaceSerializer(place_list,many=True).data})