错误http状态代码必须是整数,

时间:2018-04-19 17:16:31

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

我正在尝试序列化我的视图,并且我得到关于http状态代码必须是整数的这个错误,我没有看到必须是整数的数据在哪里并且作为字符串传递。我会感谢任何帮助,我是django的新手。 我的 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__'

我得到关于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 :(得分:1)

您在此处将四个单独的词典传递给Response。你应该传递一个:

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
  }
)