I am using the Django rest framework and Djoser for Authentication and User Registration.
When a new user registers, Djoser sends an activation email with a link that does a GET request. In order to activate, I need to extract the uid and token from the activation URL and make a POST request for Djoser to be able to activate the user.
My environment is Python 3 and Django 1.11, Djoser 1.0.1.
What I would like to do is to handle the get request in Django, extract the uid and token, and then make a POST request. I have extracted the uid and token and would like to make a POST (within this GET request). I do not know how to make this POST request in the background.
My URL is like this:
http://127.0.0.1:8000/auth/users/activate/MQ/4qu-584cc6772dd62a3757ee
When I click on this in an email it does a GET request.
I handle this in a Django view.
The view needs to make a POST request like this:
http://127.0.0.1:8000/auth/users/activate/
data= [(‘uid’=‘MQ’), (‘token’=‘4qu-584cc6772dd62a3757ee’),]
My view to handle GET is:
from rest_framework.views import APIView
from rest_framework.response import Response
import os.path, urllib
class UserActivationView(APIView):
def get (self, request):
urlpathrelative=request.get_full_path()
ABSOLUTE_ROOT= request.build_absolute_uri('/')[:-1].strip("/")
spliturl=os.path.split(urlpathrelative)
relpath=os.path.split(spliturl[0])
uid=spliturl[0]
uid=os.path.split(uid)[1]
token=spliturl[1]
postpath=ABSOLUTE_ROOT+relpath[0]+'/'
post_data = [('uid', uid), ('token', token),]
result = urllib.request.urlopen(postpath, urllib.parse.urlencode(post_data).encode("utf-8"))
content = result.read()
return Response(content)
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
import requests
class UserActivationView(APIView):
def get (self, request, uid, token):
protocol = 'https://' if request.is_secure() else 'http://'
web_url = protocol + request.get_host()
post_url = web_url + "/auth/users/activate/"
post_data = {'uid': uid, 'token': token}
result = requests.post(post_url, data = post_data)
content = result.text
return Response(content)
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^auth/users/activate/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', UserActivationView.as_view()),
]