def create(self, request, *args, **kwargs): print("PK::: ", request.user.pk) ed_programs_ids = request.data["education_programs_ids"] for ed_program_id in ed_programs_ids: favorite = Favorite(user_id=request.user.pk, education_program_id=ed_program_id) favorite.save() return Response(status=status.HTTP_201_CREATED)
def change_paste_favorite(request): """ Add/remove paste from user's favorites, and respond with JSON """ response = {"status": "success", "data": {}} char_id = None or request.POST["char_id"] action = None or request.POST["action"] if not request.user.is_authenticated(): response["status"] = "fail" response["data"]["message"] = "Not logged in." else: paste = cache.get("paste:%s" % char_id) if paste == None: try: paste = Paste.objects.select_related("user").get(char_id=char_id) cache.set("paste:%s" % char_id, paste) except ObjectDoesNotExist: cache.set("paste:%s" % char_id, False) response["status"] = "fail" response["data"]["message"] = "The paste has been removed and can no longer be added to favorites." return HttpResponse(json.dumps(response)) elif paste == False: response["status"] = "fail" response["data"]["message"] = "The paste has been removed and can no longer be added to favorites." return HttpResponse(json.dumps(response)) if action == "add": if Favorite.objects.filter(user=request.user, paste=Paste.objects.get(char_id=char_id)).exists(): response["status"] = "fail" response["data"]["message"] = "You can't favorite a paste multiple times" return HttpResponse(json.dumps(response)) favorite = Favorite(user=request.user, paste=Paste.objects.get(char_id=char_id)) favorite.save() cache.set("paste_favorited:%s:%s" % (request.user.username, char_id), True) # Update/clear related cache entries con = get_redis_connection() con.delete("user_favorite_count:%s" % request.user.username) response["data"]["char_id"] = char_id response["data"]["favorited"] = True elif action == "remove": result = Favorite.objects.filter(user=request.user, paste__char_id=char_id).delete() cache.set("paste_favorited:%s:%s" % (request.user.username, char_id), False) # Update/clear related cache entries con = get_redis_connection() con.delete("user_favorite_count:%s" % request.user.username) response["data"]["char_id"] = char_id response["data"]["favorited"] = False else: response["status"] = "fail" response["data"]["message"] = "Valid action wasn't provided." return HttpResponse(json.dumps(response))