def register_user(request): token_generator = AppTokenGenerator() data = {'username':request.data["userName"], 'password':request.data["password"], 'email':request.data["email"]} user_serializer = UserSerializer(data=data) if user_serializer.is_valid(): user = user_serializer.save() data = {'user_id':user.id,'first_name':request.data["firstName"], 'last_name':request.data["lastName"], 'email':request.data["email"], 'birth_date':None, 'country':None} profile_serializer = ProfileSerializer(data=data) if profile_serializer.is_valid(): profile_serializer.save() else: logger.error(profile_serializer.errors) login(request, user) logger.info("Preparing email...") FRONTEND_URL = settings.FRONTEND_URL BACKEND_URL = settings.BACKEND_URL # token = get_random_string(length=32) token = token_generator.make_token(user) verify_link = FRONTEND_URL + 'verify-email/' + token subject, from_email, to = 'Verify your email', settings.EMAIL_HOST_USER, request.data["email"] html_content = render_to_string('verify_email.html', {'verify_link': verify_link, 'base_url': FRONTEND_URL, 'backend_url': BACKEND_URL}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to, '*****@*****.**']) msg.attach_alternative(html_content, "text/html") msg.send() logger.info("Verification email sent") return Response({'user': user_serializer.data}) else: logger.error(user_serializer.errors)
def post(self, request, format=None): print("Creating new profile") serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None): profile = self.get_object(pk) # Partial = True allows a Patch. django-rest-framework.org/api-guide/serializers/#partial-updates serializer = ProfileSerializer(profile, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_profile(user, *args, **kwargs): if Profile.objects.filter(user=user).exists(): pass else: # Will this work with other OAuth services, or do we need to look at kwargs['backend'] and get the data appropriately from kwargs? data = {'user_id':user.id,'first_name': kwargs['details']['first_name'], 'last_name': kwargs['details']['last_name'], 'email': kwargs['details']['email'], 'birth_date':None, 'country':None} profile_serializer = ProfileSerializer(data=data) if profile_serializer.is_valid(): profile_serializer.save()