51👍
You’re getting this error as the HyperlinkedIdentityField
expects to receive request
in context
of the serializer so it can build absolute URLs. As you are initializing your serializer on the command line, you don’t have access to request and so receive an error.
If you need to check your serializer on the command line, you’d need to do something like this:
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from .models import Person
from .serializers import PersonSerializer
factory = APIRequestFactory()
request = factory.get('/')
serializer_context = {
'request': Request(request),
}
p = Person.objects.first()
s = PersonSerializer(instance=p, context=serializer_context)
print s.data
Your url field would look something like http://testserver/person/1/
.
26👍
I have two solutions…
urls.py
1)
If you are using a router.register, you can add the base_name:
router.register(r'users', views.UserViewSet, base_name='users')
urlpatterns = [
url(r'', include(router.urls)),
]
2)
If you have something like this:
urlpatterns = [
url(r'^user/$', views.UserRequestViewSet.as_view()),
]
You have to pass the context to the serializer:
views.py
class UserRequestViewSet(APIView):
def get(self, request, pk=None, format=None):
user = ...
serializer_context = {
'request': request,
}
serializer = api_serializers.UserSerializer(user, context=serializer_context)
return Response(serializer.data)
Like this you can continue to use the url on your serializer:
serializers.py
...
url = serializers.HyperlinkedIdentityField(view_name="user")
...
- [Django]-How do you use the django-filter package with a list of parameters?
- [Django]-How to fix " AttributeError at /api/doc 'AutoSchema' object has no attribute 'get_link' " error in Django
- [Django]-How can I find the intersection of two Django querysets?
14👍
I came across the same problem. My approach is to remove ‘url’ from Meta.fields in serializer.py.
- [Django]-Set up a scheduled job?
- [Django]-Get SQL query count during a Django shell session
- [Django]-Django forms, inheritance and order of form fields
4👍
Following Slipstream’s answer, I edited my views.py
introducing the context and now it works.
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().select_related('profile').order_by('-date_joined')
serializer_class = UserSerializer
@list_route(methods=['get'], url_path='username/(?P<username>\w+)')
def getByUsername(self, request, username):
serializer_context = {
'request': request,
}
user = get_object_or_404(User, username=username)
return Response(UserSerializer(user, context=serializer_context).data, status=status.HTTP_200_OK)
- [Django]-Sending an SMS to a Cellphone using Django
- [Django]-Django + Ajax
- [Django]-Is it possible to decorate include(…) in django urls with login_required?
3👍
You can simply pass None
to 'request'
key in context
in situations where you just need the relative URL, e.g; testing a serializer in command line.
serializer = YourModelSerializer(modelInstance_or_obj, context={'request': None})
- [Django]-Location of Django logs and errors
- [Django]-Django model field by variable
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
1👍
Following MDT’s response, I use django-rest-framework, and solve it by changing request to request._request.
serializer_context = {'request': Request(request._request)}
- [Django]-How to customize user profile when using django-allauth
- [Django]-Substring in a django template?
- [Django]-How to query directly the table created by Django for a ManyToMany relation?
1👍
You may simply solve it by changing the instantiation (in views.py) to thing like this:
your_serializer = YourModelSerializer(YourQuerySet_or_object, many=True,context={'request':request})
- [Django]-Is not JSON serializable
- [Django]-How do I see stdout when running Django tests?
- [Django]-Django and domain driven design
1👍
For externals urls you can simply put request at None:
context={
'request': None
},
- [Django]-Empty Label ChoiceField Django
- [Django]-STATIC_ROOT vs STATIC_URL in Django
- [Django]-How to expire Django session in 5minutes?
0👍
In my case I had to change a field’s name from url to any other thing. Hate automagic
- [Django]-Django models – how to filter number of ForeignKey objects
- [Django]-How to run own daemon processes with Django?
- [Django]-How can I set a default value for a field in a Django model?