Created
August 14, 2018 05:43
-
-
Save mayait/8ac151ec3aa71d5e87348480d0068696 to your computer and use it in GitHub Desktop.
Django push notifications subscription script for registered users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<link rel="manifest" href="/manifest.json" /> | |
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script> | |
<script> | |
var OneSignal = window.OneSignal || []; | |
// Register the client in onesignal | |
OneSignal.push(function() { | |
OneSignal.init({ | |
appId: "d4fd97fc-xxxx-xxxx-xxxxx-xxxxxxxxx", | |
safari_web_id: 'web.onesignal.auto.08e72fe8-xxxx-xxxx-xxxx-xxxxxxxxxx', | |
}); | |
}); | |
// Post onesignal playerid to django via ajax every time the user load the page | |
OneSignal.getUserId( function(userId) { | |
console.log('player_id of the subscribed user is : ' + userId); | |
// Make sure to change the URL for the correct path | |
$.post("/onesignal-register/", | |
{ | |
playerId: userId, | |
csrfmiddlewaretoken: "{{ csrf_token }}", | |
}, | |
function(data, status){ | |
console.log("Data: " + data + "\nStatus: " + status); | |
}); | |
}); | |
}); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# add the path route for the view in the urls.py of your app. | |
urlpatterns += [ | |
path('onesignal_register/', views.onesignal_register, name='onesignal_register'), | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponse | |
@login_required | |
def onesignal_register(request): | |
'''Receives the onesignal playerid of this user''' | |
profile = Profile.objects.get(user=request.user) # The model where you will to save the profile. | |
if request.POST.get('playerId'): | |
profile.onesignal_playerId = request.POST.get('playerId') | |
profile.save() | |
return HttpResponse('Done') | |
return HttpResponse('Something went wrong') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment