简体   繁体   中英

How to set cookie on DRF viewset?

I'd like to know how to set a cookie on Django rest framework ViewSet/ModelViewSet.

I read some SO posts that say you can use Response({serializer.data}) , but in retrieve it may be okay, but for create() like the following one, doesn't Response() affect its following processing?

Actually when I used HttpResponse() like HttpResponse(status=401, reason="you cannot post anymore.") replacing the raise PermissionDenied() line in the below one, I got a 500 error (error says AttributeError: 'collections.OrderedDict' object has no attribute 'pk' or such) but not the specified 401 code.

So basically the following explains what I want to do, that is denies when the user's post count is >= 4, but otherwise continues perform_create() and the following DRF script, with attaching a cookie, that tells browser "you have n post slots left".

class PostViewSet(viewsets.ModelViewSet):
    ..

  def perform_create(self, serializer):

      role = self.request.user.userproperty.role
      if role == "guest":
          post_count = self.request.user.posts.count()
          if post_count >= 4:
              raise PermissionDenied({"message": "you cannot post anymore."})
          else:
              response = // anyhow gets response here //
              response.set_cookie("notify", "your post slot is " + str(3 - post_count) + "left now.")

      serializer.save(user=self.request.user)

But I don't know how can I possibly get response from something, or calling Response() without harming consequences script.

I tried, but didn't work (as I could expect):

  1. self.request.COOKIES["new_cookie"] = "test."
  2. self.response .

It seems I didn't have an enough research. I found a solve:

    def create(self, request, *args, **kwargs):
        response = super().create(request, args, kwargs)

        // whatever 

        response.set_cookie("_hoge", "hogee.")

        return response

The point is that perform_create() doesn't deal with Response(), while create() does; since create() calls perform_create(), it was no problem to move the block to create().

Reference: Adding extra data to Django Rest Framework results for entire result set - Stack Overflow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM