Home > Blockchain >  Django Rest Framework how do I get the id I use in the URL
Django Rest Framework how do I get the id I use in the URL

Time:01-21

I have this serializer and I use it to get post detail of a post belonging to a user. The owner of the post is not the user that is currently logged in. I want to check if the post is bookmarked by the currently logged in user. The currently logged in user's id is passed in the request but I cannot find it in this context.

Here is the serializer:

class UserPostSerializer(serializers.ModelSerializer):
    images = PostImageSerializer(many=True, read_only=True, required=False)
    profile = serializers.SerializerMethodField()
    bookmarked = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = [
            "id",
            "category",
            "body",
            "images",
            "video",
            "profile",
            "published",
            "bookmarked",
            "created_at",
            "updated_at",
        ]
        depth=1
        
    def get_profile(self, obj):
        profile_obj = Profile.objects.get(id=obj.user.profile.id)
        profile = ShortProfileSerializer(profile_obj)
        return profile.data

    def get_bookmarked(self, obj):
        breakpoint()
        bookmark = Bookmark.objects.filter(owner=obj.user.id, post=obj.id,marktype='post')
        if bookmark:
            return True
        else:
            return False

The problem is obj.user.id is the owner of the post. I need the logged in user whose id is passed in the url. Here is the model for the bookmark:

class Bookmark(models.Model):
    marktype = models.CharField(max_length=50)
    post = models.OneToOneField(Post, on_delete=models.CASCADE, null=True, blank=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at")

    class Meta:
        verbose_name = "bookmark"
        verbose_name_plural = "bookmarks"
        ordering = ["created_at"]
        db_table = "bookmarks"

    def __str__(self):
        return "{}'s bookmark".format(self.owner.username)

and here is the URL:

path("posts/<int:user>/home/", HomeView.as_view(), name="home"),

This self.context['request'].user returns the owner of the post and not the logged in user. How do I get the id of the currently logged in user or the user whose id I pass in the URL please?

CodePudding user response:

Maybe do you can use filters to the Viewset:

urls.py

path("posts/home/", HomeView.as_view(), name="home")

viewsets.py

from rest_framework import viewsets

from .models import Post
from .serializers import, UserPostSerializer
from .filters import OwnerFilter


class HomeView(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = UserPostSerializer
    filter_backends = (OwnerFilter,)

filters.py

from rest_framework.filters import BaseFilterBackend

class OwnerFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        owner = request.query_params.get('owner', None)

        if not owner:
            return queryset.all()
        else:
            try:
                return queryset.filter(bookmarked__owner__id=owner)
            except Exception:
                return queryset.none()

Running

Then access the URL: /posts/home/?owner=OWNER_ID_HERE

CodePudding user response:

Solved it and you can get any kwargs from the view that handles the request. In my case adding the following to the get_bookmarked function gives me the id I send in the URL:

loggeduser = self.context.get('view').kwargs.get('user')
  • Related