django rest framework - request context key error - json

I have two models (Like and News). I am using django-rest-framework to make a web api out of it.
class Like(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class News(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=150)
...
likes = GenericRelation(Like)
A Like object has its own user field to store who liked the News object. Now to check if a specific user exists in any of the likes of a News object, I am getting request.user from a SerializerMethodField.
class NewsSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
likes_count = serializers.IntegerField(source='likes.count', read_only=True)
user_in_likes = serializers.SerializerMethodField()
class Meta:
model = News
fields = ('user', 'title', 'body', 'article_image', 'pub_date', 'likes_count', 'user_in_likes')
def get_user_in_likes(self, obj):
user = self.context['request'].user
what = obj.likes.filter(user=user).exists()
return what
When I go the /news/ url, I get the json objects including the user_in_likes to true/false for each news object.
However, I have another serialzer for different model which imports NewsSerializer class and other similar serializers:
class ActivityObjectRelatedField(serializers.RelatedField):
def to_representation(self, value):
if isinstance(value, User):
serializer = UserSerializer(value)
elif isinstance(value, Job):
serializer = JobSerializer(value)
elif isinstance(value, News):
serializer = NewsSerializer(value)
elif isinstance(value, Tender):
serializer = TenderSerializer(value)
else:
raise Exception('Unexpected type of tagged object')
return serializer.data
class ActivitySerializer(serializers.HyperlinkedModelSerializer):
actor = ActivityObjectRelatedField(read_only=True)
target = ActivityObjectRelatedField(read_only=True)
class Meta:
model = Activity
fields = ('url', 'actor', 'verb', 'target', 'pub_date')
Now if I visit /activities/, to get the activities objects I am getting an error:
KeyError at /activities/
'request'
And it points to the line of SerializerMethod of NewsSerialize class where self.context['request'].user is used.
Exception Location: /vagrant/myproject/news/serializers.py in get_user_in_likes, line 25
Again if I visit /news/ url, everything is fine and I get news objects. What am I missing here? Why is request not being recognized in the ActivitiesSerializer class? Please help me solve this problem. Thank you.

You are getting this error because you are not passing request in the context when instantiating the NewsSerializer class or other similar serializers in the to_representation() method.
You are manually instantiating the particular serializer class in to_representation() method. So, after instantiation, that particular serializer does not have access to ActivitySerializer's context thereby leading to the error.
You can pass the ActivitySerializer's context during instantiation of the relevant serializer in the to_representation() method.
class ActivityObjectRelatedField(serializers.RelatedField):
def to_representation(self, value):
if isinstance(value, User):
serializer = UserSerializer(value, context=self.context) # pass context
elif isinstance(value, Job):
serializer = JobSerializer(value, context=self.context) # pass context
elif isinstance(value, News):
serializer = NewsSerializer(value, context=self.context) # pass context
elif isinstance(value, Tender):
serializer = TenderSerializer(value, context=self.context) # pass context
else:
raise Exception('Unexpected type of tagged object')
return serializer.data

It seems like you don't populate the context dictionary of NewsSerializer with your request in the /activities/ view.
You probably use a class based view provided by Django REST Framework which populates this dictionary for you (see the get_serializer_context() method) and passes it to the Serializer instance. That's why it's automatically available to your serializer in your /news/ view.
In your /activities/ view, though, the context is passed to ActivitySerializer and isn't (automatically) propagated further from there. That's why there's no request key in your context dictionary of NewsSerializer. You would need to pass your request object to the NewsSerializer instance. To pass extra context to a Serializer you can add a context parameter containing a dictionary when instantiating (see the DRF documentation).

Related

Serializing Django FilterSet

I'm using django-filter (https://django-filter.readthedocs.io/en/stable/guide/install.html).
How can I serialize the Filterset in order to send it back to my angular Frontend?
views.py:
#api_view(['GET'])
def materialien_search(request):
filter = MaterialFilter(request.GET, queryset=Materialien.objects.all())
materialien_serializer = MaterialienSerializer(filter, many=True)
return JsonResponse(materialien_serializer.data, safe=False)
serializers.py:
class MaterialienSerializer(serializers.ModelSerializer):
class Meta:
model = Materialien
fields = [field.name for field in Materialien._meta.get_fields()]
filter.py:
class MaterialFilter(django_filters.FilterSet):
class Meta:
model = Materialien
fields = '__all__'
I'd be thankful for every help.
The Filterset should be a GET QueryDict, but all my attemps of serializing or converting it to JSON failed because Materialfilter is neither iterable nor serializable. So json.dumps and json.load and
serializers.serialize("json", filter) did not work.
TypeError: 'MaterialFilter' object is not iterable
TypeError: Object of type MaterialFilter is not JSON serializable

Access Json object name

I want to get data with request.data.columns in frontend.I can do it with ViewSet with list method but how to do it with generics.APIView.
Below is my viewsets and generics code:
class TestList(viewsets.ViewSet):
queryset = Test.objects.all()
def list(self,request):
serializer = TestSerializer(self.queryset, many = True)
return Response({'columns': serializer.data})
class TestList(generics.RetriveAPIView):
queryset = Test.objects.all()
serializer_class = TestSerializer
class TestList(APIView):
queryset = Test.objects.all()
def list(self,request):
serializer = TestSerializer(self.queryset, many = True)
return Response({'columns': serializer.data})
change your urls.py like this.
path(r"url", TestList.as_view({"get": "list"}))
Correct code:
class TestList(APIView):
queryset = Test.objects.all()
def list(self,request):
queryset = self.get_queryset()
serializer = TestSerializer(queryset, many = True)
return Response({'columns': serializer.data})
Details about why i had to add queryset = self.get_queryset() instead of directly access self.queryset.From official drf documentation:
queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.

How to make QuerySet JSON serializable?

I have a problem with creating a new object in my Rest Framework.
As much I as understand, when I tried to overwrite item's field so it could have all the items that are in my database. I thought, that this would work, and it showed me the working page and I could choose an item. But when I tried to post it to create a new object, it said "Object of type 'Item' is not JSON serializable"
I was trying to figure it out, how to convert Item.objects.all() into JSON data. But nothing helped me. I understand, that this isn't really hard to do, but I can't figure it out on my own.
So I ask for your help, how to solve this problem?
Here's my serializer
from rest_framework import serializers
from items.models import OrderItem, Item
class OrderItemSerializer(serializers.ModelSerializer):
item = serializers.ChoiceField(choices=Item.objects.all())
class Meta:
model = OrderItem
fields = ('item', 'size', 'quantity', 'id')
from rest_framework import serializers
from items.models import OrderItem, Item
class OrderItemSerializer(serializers.ModelSerializer):
item = serializers.SerializerMethodField()
class Meta:
model = OrderItem
fields = ('item', 'size', 'quantity', 'id')
def get_item (self, obj):
# in value list name all fields u want or empty for defaults
return Item.objects.all().values_list('pk', flat=True)
...
and inside the create method (post in Serializer)
...
def create(self, validated_data):
req = self.context.get('request')
items = req.data.get('item')
if items:
[OrderItem.item.add(
oneitem) for oneitem in items]

Django REST bulk post / post array of JSON objects

I have started to play around with the Django REST framework. So far I succeeded in creating a serializer for my object, creating the post view, post objects and return objects via Javascript's $.post(). So right now I have a proper conversion between my JSONs and Django model objects.
The problem is that I have an array of objects [A1, A2, ..., An]. Right now when I need to post such an array I do it object by object. Is there any possibility to post the whole array at once, and recover an array of objects inside my Django View? If so, what is the pattern to follow here? I guess I could define a new model which is an array of my current model, create a serializer for it, etc., but this does not seem too elegant.
Below are my view and serializer:
#serializers.py
class SearchRequestSerializer(serializers.ModelSerializer):
def create(self):
return SearchRequest(**self.validated_data)
class Meta:
model = SearchRequest
#views.py
#api_view(['POST'])
def post_calculation(request):
if request.method == 'POST':
#JSON to serializer object
serializer = SearchRequestSerializer(data=request.data, many=False)
if (serializer.is_valid() == False):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#create the Python object
search_request = serializer.create()
#-- I do some processing stuff with the search_request object here ---
#object back to JSON
serializer3 = SearchRequestSerializer(search_request, many=False)
return Response(serializer3.data)
There are two solutions to your problem:
The first solution is to override the .create() method of your view
By default, django rest framework assumes you are passing it a single object. To account for the possibility to pass it a list of objects you might rewrite it as follows:
def create(self, request, pk=None, company_pk=None, project_pk=None):
is_many = isinstance(request.data, list)
serializer = self.get_serializer(data=request.data, many=is_many)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Now your view will handle both single objects in POST data as well as a list of objects.
The second solution is to use a third party package
django-rest-framework-bulk provides the above functionality plus additional features (e.g. bulk update). You can check it out and decide whether it fits your needs.
Update: The solution for function based views
In order to get it to work with your function based view, the approach is similar:
#api_view(['POST'])
def post_calculation(request):
if request.method == 'POST':
is_many = isinstance(request.data, list)
# JSON to serializer object
serializer = SearchRequestSerializer(data=request.data, many=is_many)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
#-- do some processing stuff here ---
return Response(serializer.data)
Do not call .create() method directly, use .save() instead. Also, when using many=False on serializer, the created instance is available under serializer.instance. I am not sure how to obtain the list of created instances though. You can try the same serializer.instance. If it doesn't work, try to find how to get it.

Django REST: ContentNotRenderedError when checking JSON object before rendering

I have a Django model, Note, which has a class-based view. It is supposed to return a JSON object upon the appropriate query.
Before returning the object, however, I would like to check that the user field in the note object matches the user currently logged in. (Users should not be able to access Note objects that are not their own.) To do this, I tried rewriting the get() method, calling on self.retrieve() to inspect the object before returning it:
class NoteDetail(generics.RetrieveUpdateDestroyAPIView):
model = Note
serializer_class = NoteSerializer
permission_classes = (permissions.IsAuthenticated,)
renderer_classes = (JSONRenderer,)
def get(self, request, *args, **kwargs):
current_user = User.objects.get(pk=self.request.user.id)
note = self.retrieve(request, *args, **kwargs)
if note.author is current_user:
return note
else:
raise PermissionDenied('Note does not belong to authenticated user.')(author=current_user)
However, this returns a ContentNotRenderedError when run: The response content must be rendered before it can be accessed.
Is there a way for me to check the object before returning it? Must I find a workaround?
One potential workaround is to redefine get_queryset(), rather than get() or get_object(). get_queryset() is the function that returns all objects of the relevant model; get_object() narrows down among these given the argument pk.
By overriding get_queryset(), you restrict the potential objects that get_object() can pick. Thus the set is already filtered at the time get() is called.
def get_queryset(self):
current_user = User.objects.get(pk=self.request.user.id)
# Must filter by author to prevent making everyone's notes public
queryset = Note.objects.filter(author=current_user)
return queryset