i am trying to get data from django server and get this error.
Internal Server Error: /data/site-info/
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "/Users/hco/PycharmProjects/tool/linyit/data/views.py", line 17, in site_info
Response(serializer.data)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 674, in data
ret = super(ListSerializer, self).data
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 239, in data
self._data = self.to_representation(self.instance)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 614, in to_representation
self.child.to_representation(item) for item in iterable
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 459, in to_representation
fields = self._readable_fields
File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 353, in _readable_fields
field for field in self.fields.values()
AttributeError: 'tuple' object has no attribute 'values'
my_app/urls.py:
urlpatterns = [
url(r'^site-info/$', site_info, name='site_info'),
]
my_app/models.py:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class SiteInfo(models.Model):
site_id = models.IntegerField(primary_key=True)
site_name = models.CharField(max_length=100, blank=True, null=True)
latitude = models.DecimalField(max_digits=18, decimal_places=15, blank=True, null=True)
longitude = models.DecimalField(max_digits=18, decimal_places=15, blank=True, null=True)
class Meta:
# managed = False
db_table = 'site_info'
data/views:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import SiteInfo
from .serializers import SiteInfoSerializer
# Create your views here.
#api_view(['GET', 'POST'])
def site_info(request):
"""
List all sites
"""
if request.method == 'GET':
sites = SiteInfo.objects.using('teldata').all()
serializer = SiteInfoSerializer(sites, many=True)
Response(serializer.data)
my_app/serializers:
from rest_framework import serializers
from .models import SiteInfo
class SiteInfoSerializer(serializers.ModelSerializer):
model = SiteInfo
fields = ('site_id', 'site_name', 'latitude', 'longitude')
what could be the problem? thanks
Your serializer needs to use a nested Meta class to declare model and fields (you were declaring them as normal attributes of the class instead of nesting them):
class SiteInfoSerializer(serializers.ModelSerializer):
class Meta:
model = SiteInfo
fields = ('site_id', 'site_name', 'latitude', 'longitude')
by adding (class Meta) in serializers.py the error can get solved as per my error which i were getting.
the image which shows code of serializers.py
Related
I am trying to create a POST request to add a user to a database, but I am getting a 500 error with this message: AttributeError: 'QuerySet' object has no attribute '_meta'. Here is my code:
#api_view(['POST'])
def register(request):
data = request.data
if data['password'] != data['password_confirm']:
raise exceptions.APIException('Passwords do not match')
serializer = UserSerializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
UserSerializer:
from rest_framework import serializers
from users.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User.objects.all()
fields = ['id', 'first_name', 'last_name', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
User:
from django.db import models
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=63)
last_name = models.CharField(max_length=63)
email = models.CharField(max_length=255, unique=True)
password = models.CharField(max_length=255)
This is the stack trace:
Internal Server Error: /api/register
Traceback (most recent call last):
File "/home/amicharski/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/amicharski/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/amicharski/.local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/amicharski/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/decorators.py", line 50, in handler
return func(*args, **kwargs)
File "/home/amicharski/PycharmProjects/admin/users/views.py", line 16, in register
serializer.is_valid(raise_exception=True)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 220, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 419, in run_validation
value = self.to_internal_value(data)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 472, in to_internal_value
for field in fields:
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 355, in _writable_fields
for field in self.fields.values():
File "/home/amicharski/.local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 349, in fields
for key, value in self.get_fields().items():
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 1028, in get_fields
info = model_meta.get_field_info(model)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/utils/model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'QuerySet' object has no attribute '_meta'
These are the kinds of errors that take 8 hours to solve but the solution is to change 1 line of code. I just had to shorten User.objects.all() in serializers.py on line 8 just to User, so line 8 is now: model = User.
I have the following model classes.
class Categories(models.Model):
id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True)
business = models.ForeignKey(Business, related_name='category_business', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
class Meta:
unique_together = ('business', 'name')
class Menu(models.Model):
id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True)
business = models.ForeignKey(Business, related_name='menu_business', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
description = models.CharField(max_length=128)
category = models.ForeignKey(Categories, related_name='menus', on_delete=models.CASCADE)
price = models.IntegerField()
class Meta:
unique_together = ('business', 'name', 'category')
def __str__(self):
return '%s %s %s' % (self.name, self.price, self.description)
and I have imported these classes as following as they are located in a separate package
Categories = apps.get_model('business', 'Categories')
Menu = apps.get_model('business', 'Menu')
and this is my serializer class
class GetCategoriesSerializer(serializers.ModelSerializer):
menus = serializers.StringRelatedField(many=True)
class Meta:
model = Categories
fields = ('name', 'menus')
and views is
class GetCategories(generics.ListAPIView):
"""
Returns a list of businesses to the user. It'd read only and no authentication is needed
"""
permission_classes = [ReadOnly]
queryset = Categories.objects.values()
serializer_class = GetCategoriesSerializer
and url has the following
path('customer/<str:pk>/categories', GetCategories.as_view()),
I am getting the following error
Traceback (most recent call last):
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/generics.py", line 199, in get
return self.list(request, *args, **kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/mixins.py", line 48, in list
return Response(serializer.data)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 760, in data
ret = super().data
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 678, in to_representation
self.child.to_representation(item) for item in iterable
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 678, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 516, in to_representation
attribute = field.get_attribute(instance)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/relations.py", line 529, in get_attribute
relationship = get_attribute(instance, self.source_attrs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/fields.py", line 92, in get_attribute
instance = instance[attr]
Exception Type: KeyError at /customer/85f44d20-f936-4940-8e15-01393e42c4a8/categories
Exception Value: 'menus'
I looked into the DRF example and this seems to be a simple thing to achieve.
https://www.django-rest-framework.org/api-guide/relations/#api-reference
But I am kind of stuck at this point. Am I doing anything wrong? Thanks in advance for any help.
You should've used the QuerySet instead of ValueQuerySet. That is use queryset = Categories.objects.all() instead of queryset = Categories.objects.values()
So change the queryset attribute of the view as,
class GetCategories(generics.ListAPIView):
permission_classes = [ReadOnly]
queryset = Categories.objects.all()
serializer_class = GetCategoriesSerializer
In my quiz app, every user can have multiple attempts. My model setup is as follows:
class Quiz(models.Model):
title = models.CharField(max_length=15)
slug = models.SlugField(blank=True)
questions_count = models.IntegerField(default=0)
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
label = models.CharField(max_length=1000)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
answer = models.CharField(max_length=100)
is_correct = models.BooleanField('Correct answer', default=False)
class QuizTaker(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
correct_answers = models.IntegerField(default=0)
completed = models.BooleanField(default=False)
attempt_number = models.PositiveIntegerField(default=0)
I get the error in my serializer when I try to determine if a given quiz has been completed:
class MyQuizListSerializer(serializers.ModelSerializer):
questions_count = serializers.SerializerMethodField()
completed = serializers.SerializerMethodField()
progress = serializers.SerializerMethodField()
score = serializers.SerializerMethodField()
class Meta:
model = Quiz
fields = ['id', 'title', 'type_of_content', 'song', 'slug',
'questions_count', 'completed', 'score', 'progress']
read_only_fields = ['questions_count', 'completed', 'progress']
def get_completed(self, obj):
try:
quiztaker = QuizTaker.objects.filter(user=self.context['request'].user, quiz=obj)
for attempt in quiztaker:
return quiztaker.completed #the error comes from this line
except QuizTaker.DoesNotExist:
return None
Can anybody tell me why I am getting this error? I am filtering because the user can have multiple attempts, therefore I get a queryset, and therefore I must loop through it. The QuizTaker model does have a completed field, so what is the issue?
Here is the full traceback:
Traceback (most recent call last):
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\generics.py", line 199, in get
return self.list(request, *args, **kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\mixins.py", line 46, in list
return Response(serializer.data)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 760, in data
ret = super().data
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation
return [
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 678, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\fields.py", line 1905, in to_representation
return method(value)
File "C:\Users\mvren\OneDrive\Documents\Coding\Russki\mysite\quizzes\serializers.py", line 48, in get_completed
return quiztaker.completed
Exception Type: AttributeError at /quizzes/api/my-quizzes/Melissavr
Exception Value: 'QuerySet' object has no attribute 'completed'
Simple mistake, the quiztaker object is a QuerySet.
You should be using the attempt variable assigned in the for loop:
for attempt in quiztaker:
return attempt.completed #the error comes from this line
I've been playing around with the mongoengine framework and came across the above mentioned exception. Seems like I'm missing something and that's what I would like to clarify, hopefully with your help.
Here is my MSV:
models.py
import mongoengine
class PersonAddressModel(mongoengine.DynamicEmbeddedDocument):
country = mongoengine.fields.StringField()
town = mongoengine.fields.StringField()
class PersonInfoModel(mongoengine.DynamicDocument):
name = mongoengine.fields.StringField()
age = mongoengine.fields.IntField()
is_married = mongoengine.fields.BooleanField()
address = mongoengine.fields.MapField(
mongoengine.fields.EmbeddedDocumentField(
PersonAddressModel
)
)
serializers.py
from rest_framework_mongoengine import serializers
from .models import PersonInfoModel, PersonAddressModel
class PersonAddressSerializer(serializers.EmbeddedDocumentSerializer):
class Meta:
model = PersonAddressModel
fields = '__all__'
class PersonInfoSerializer(serializers.DocumentSerializer):
def create(self, validated_data):
return PersonInfoModel.objects.create(**validated_data)
class Meta:
model = PersonInfoModel
fields = '__all__'
views.py
from rest_framework_mongoengine import viewsets
from .serializers import PersonInfoSerializer
from rest_framework.response import Response
from rest_framework import status
import djongo
class PersonInfoView(viewsets.ModelViewSet):
lookup_field = 'id'
serializer_class = PersonInfoSerializer
def create(self, request):
serializer = self.serializer_class(data=request.data)
try:
serializer.is_valid(raise_exception=True)
serializer.save()
except djongo.sql2mongo.SQLDecodeError:
return Response(
status=status.HTTP_503_SERVICE_UNAVAILABLE
)
return Response(
status=status.HTTP_201_CREATED
)
Here is the json object I'm trying to post:
{
"name": "John",
"age": 20,
"is_married": false,
"address": {
"country": "Canada",
"town": "Toronto"
}
}
But it doesn't work, what am I failing to understand about all this?
EDIT
Here is the server traceback:
Internal Server Error: /api/v1/person
Traceback (most recent call last):
File "/home/dop/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/dop/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/dop/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/dop/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/viewsets.py", line 95, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/home/dop/Documents/projects/serverside/essences/person/views.py", line 17, in create
serializer.save()
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py", line 184, in save
'You cannot call `.save()` on a serializer with invalid data.'
AssertionError: You cannot call `.save()` on a serializer with invalid data.
I have two models, Roundtrip and Tour, and another model called RoundtripTour where I can link those two models in a many-to-many fashion. I have made a rest service that returns a Tour instance and a list of all RoundtripTour instances through a reverse reference, and it works perfectly, but the service returns all fields from the RoundtripTour model, and I want to return only the field that references the Roundtrip model instance.
These are my models:
class Roundtrip(models.Model):
name = models.CharField(max_length=70, verbose_name=_('Name'))
code = models.CharField(max_length=8, verbose_name=_('Code'))
duration = models.IntegerField(verbose_name=_('Duration'))
description = models.TextField(verbose_name=_('Description'))
class Tour(models.Model):
name = models.CharField(max_length=70, verbose_name=_('Name'))
description = models.TextField(verbose_name=_('Description'))
is_own = models.BooleanField(default=True, verbose_name=_('Is own tour?'))
code = models.CharField(max_length=10, verbose_name=_('Code'))
class RoundtripTour(models.Model):
roundtrip = models.ForeignKey(Roundtrip, on_delete=models.PROTECT, related_name='tours', verbose_name=_('Roundtrip'))
tour = models.ForeignKey(Tour, on_delete=models.PROTECT, related_name='roundtrips', verbose_name=_('Tour'))
day = models.IntegerField(verbose_name=_('Day'))
This is my serializer:
class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer):
roundtrips = serializers.SerializerMethodField()
def get_roundtrips(self, instance):
queryset = [x.roundtrip for x in instance.roundtrips.all()]
return RoundtripSerializer(queryset, many=True, context=self.context).data
class Meta:
model = models.Tour
fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips')
This is my view:
class TourRoundtripsViewSet(viewsets.ModelViewSet):
queryset = models.Tour.objects.all()
serializer_class = serializers.TourRoundtripsSerializer
I would like the roundtrips reverser reference to return only the field roundtrip from the RoundtripTour model (roundtrip field of RoundtripTour model). Is that possible?
I made the changes suggested by #Ykh, but I get an error. This is the traceback:
Internal Server Error: /es/reservations_manager/roundtrips/1/composition
Traceback (most recent call last):
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/mixins.py", line 58, in retrieve
return Response(serializer.data)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 560, in data
ret = super(Serializer, self).data
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/fields.py", line 1855, in to_representation
return method(value)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/Intellibook/ReservationsManagerApp/serializers.py", line 191, in get_hotels
return HotelSerializer(queryset, many=True).data
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 765, in data
ret = super(ListSerializer, self).data
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation
self.child.to_representation(item) for item in iterable
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/relations.py", line 356, in to_representation
"the serializer." % self.__class__.__name__
AssertionError: `HyperlinkedRelatedField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.
[24/May/2018 14:23:52] "GET /es/reservations_manager/roundtrips/1/composition HTTP/1.1" 500 145268
class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer):
roundtrips = serializers.SerializerMethodField()
def get_roundtrips(self, instance):
queryset = [x.roundtrip for x in instance.roundtrips.all()]
return RoundtripSerializer(queryset, many=True, context=self.context).data
class Meta:
model = models.Tour
fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips')
depth = 1
use SerializerMethodField to get whatever you want.