예제 #1
0
def getCreateMyGridPage(request):
    if not request.user.is_authenticated():
        return redirect_to(request, '/auth/login/')
    try:
        tableOnly= False
        if request.REQUEST.has_key('tableOnly'):
            if request.REQUEST['tableOnly'] == 'true':
                tableOnly= True
    
        gridTableTemplate= GridTableData(generateGridTable(None))
        gridTableTemplate.changeRatingsWeights= True
        gridTableTemplate.changeCornAlt= True
        gridTableTemplate.tableId= randomStringGenerator()
             
        context= None 
        #RequestContext(request, {'data': gridTableTemplate })
        if tableOnly:
            template= loader.get_template('gridMng/createMyGridBase.html')
            templateData= CreateMyGridBaseData(gridTableTemplate)
            context= RequestContext(request, {'data': templateData })
            htmlData= template.render(context)
            return HttpResponse(createXmlSuccessResponse(htmlData), content_type='application/xml')
        else:
            templateData= CreateMyGridData(CreateMyGridBaseData(gridTableTemplate))
            context= RequestContext(request, {'data': templateData })
            return render(request, 'gridMng/createMyGrid.html', context_instance=context)

    except:
        #do nothing
        print "Exception in user code:"
        print '-'*60
        traceback.print_exc(file=sys.stdout)
        print '-'*60
        return HttpResponse(createXmlErrorResponse('unknown error'), content_type='application/xml')
예제 #2
0
    def form_valid(self, form):
        email = form.cleaned_data['email']
        password = form.cleaned_data['password']
        firstName = form.cleaned_data['firstName']
        lastName = form.cleaned_data['lastName']

        user = User.objects.create_user(email, email, password);
        user.first_name = firstName
        user.last_name = lastName
        if settings.EMAIL_VERIFICATION:
            user.is_active = False
        user.save();

        #login the user after creation
        user = authenticate(email= email, password= password)
        login(self.request, user);

        verificationCode = utility.randomStringGenerator(14)

        profile = user.get_profile()
        profile.verifyEmailCode = verificationCode

        emailService = EmailService()
        if emailService.sendRegistrationEmail(user, verificationCode):
            profile.save();
            return HttpResponseRedirect('/home/');
        else:
            # problem with email sending
            pass

        return super(RegistrationView, self).form_valid(form)
예제 #3
0
    def form_valid(self, form):
        email = form.cleaned_data['email']
        user = User.objects.get(email=email)
        generatedCode = utility.randomStringGenerator(14)

        code = PassRecoverCode()
        code.email = email
        code.linkCode = generatedCode

        emailService = EmailService()

        if emailService.sendForgotPasswordEmail(user, code):
            code.save()
            return self.render_to_response(self.get_context_data(form=form, checkEmail = True))
        else:
            # error in sending mail
            pass

        return super(ForgotPasswordView, self).form_valid(form)
예제 #4
0
    def form_valid(self, form):
        email = form.cleaned_data['email']
        user = User.objects.get(email=email)
        generatedCode = utility.randomStringGenerator(14)

        code = PassRecoverCode()
        code.email = email
        code.linkCode = generatedCode

        emailService = EmailService()

        if emailService.sendForgotPasswordEmail(user, code):
            code.save()
            return self.render_to_response(
                self.get_context_data(form=form, checkEmail=True))
        else:
            # error in sending mail
            pass

        return super(ForgotPasswordView, self).form_valid(form)
예제 #5
0
def createGrid(userObj, gridType,  gridName, nConcerns, nAlternatives, concernValues, alternativeValues, ratioValues, createRatios):
    
    if userObj != None and gridType != None and nConcerns != None and nAlternatives != None and concernValues != None and alternativeValues != None and ratioValues != None and createRatios != None:
        try:
            gridObj= Grid.objects.create(user= userObj, grid_type= gridType)
            if gridName != None:
                gridObj.name= gridName
            gridObj.usid = randomStringGenerator(GRID_USID_KEY_LENGTH)
            gridObj.dateTime = datetime.utcnow().replace(tzinfo=utc)
            #gridObj.dateTime = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
            try:
                gridObj.save()
            except IntegrityError as error:
                # check to see if the usid is duplicated or not
                results= Grid.objects.filter(usid= gridObj.usid)
                if len(results) >= 1:
                    #in this case the key was duplicated, so lets try to create a new key
                    maxAttempts= 5
                    wasGridSaved= False
                    while maxAttempts >= 0:
                        maxAttempts-= 1
                        key= randomStringGenerator(GRID_USID_KEY_LENGTH)
                        #check to see if this key is unique
                        results= Grid.objects.filter(usid= key)
                        if len(results) <= 0:
                            gridObj.usid= key
                            gridObj.save()
                            wasGridSaved= True
                            break
                    if wasGridSaved == False:
                        #in case we can not create a unique key, raise an error
                        raise UnablaToCreateUSID('Unable to create unique suid for the grid ' + gridName)
                    else:
                        #the integratyError was not caused by a duplicated suid so, raise it again
                        raise error
            #gridObj= Grid.objects.create(user= userObj, name= gridName)
            #print 'nAlternatives: ' + str(nAlternatives)
            
            alternatives= []
            concerns= []
            
            for i in range(int(nAlternatives)):
                alternative= Alternatives.objects.create(grid= gridObj, name= alternativeValues[i])
                alternatives.append(alternative)
            
            for i in range(int(nConcerns)):
                concern= Concerns.objects.create(grid= gridObj, leftPole= concernValues[i][0], rightPole= concernValues[i][1], weight= concernValues[i][2])
                concerns.append(concern)
            print ratioValues
            if createRatios:
                for i in range(int(nConcerns)):
                    for j in range(int(nAlternatives)):
                        Ratings.objects.create(concern= concerns[i], alternative= alternatives[j], rating= ratioValues[i][j])

            return gridObj
        except:
            try:
                gridObj.delete()
            except:
                print 'Could not delete the grid'
                print "Exception in user code:"
                print '-'*60
                traceback.print_exc(file=sys.stdout)
                print '-'*60
            raise
    else:
        raise ValueError('One or more variables were None')
예제 #6
0
def ajaxConvertSvgTo(request):
    if not request.user.is_authenticated():
        return redirect_to(request, '/auth/login/')
    fpInMemory = None
    try:
        if request.POST.has_key('data') and request.POST.has_key('fileName') and request.POST.has_key('convertTo'):
            if request.POST['convertTo'] == 'svg':
                fileName= request.POST['fileName']
                #if the file name is empty generate a file name
                if  fileName == '':
                    fileName= randomStringGenerator()
                response = HttpResponse(request.POST['data'], content_type='image/svg+xml')
                response['Content-Disposition'] = 'attachment; filename=' + fileName + '.svg'
                return response

            else:
                try:
                    (imageFileName, mimeType, fileExtention)= convertSvgTo(request.POST['data'], request.POST['convertTo'])
                    if imageFileName != None:
                        fpInMemory= BytesIO()
                        fp= open(imageFileName, "rb")
                        
                        #read the file and place it in memory
                        try:
                            byte= fp.read(1)
                            while byte != '':
                                fpInMemory.write(byte)
                                byte= fp.read(1)
                        finally:
                            fp.close()
                            os.remove(imageFileName)
                        
                        # send the file
                        response = HttpResponse(fpInMemory.getvalue(), content_type= mimeType)
                        response['Content-Length'] = fpInMemory.tell()
                        fileName= request.POST['fileName']
                        if fileName != None and fileName != '':
                            response['Content-Disposition'] = 'attachment; filename=' + fileName + fileExtention
                        else:
                            response['Content-Disposition'] = 'attachment; filename=' + randomStringGenerator() + fileExtention
                        return response
                    else:
                        errorImageData= getImageError()
                        # send the file
                        response = HttpResponse(errorImageData, content_type= 'image/jpg')
                        response['Content-Length'] = fpInMemory.tell()
                        response['Content-Disposition'] = 'attachment; filename=error.jpg' 
                        return response
                except:
                    print "Exception in user code:"
                    print '-'*60
                    traceback.print_exc(file=sys.stdout)
                    print '-'*60
                    errorImageData= getImageError()
                    # send the file
                    response = HttpResponse(errorImageData, content_type= 'image/jpg')
                    response['Content-Disposition'] = 'attachment; filename=error.jpg'
                    return response 
        else:
            errorImageData= getImageError()
            # send the file
            response = HttpResponse(errorImageData, content_type= 'image/jpg')
            response['Content-Length'] = fpInMemory.tell() if fpInMemory else None
            response['Content-Disposition'] = 'attachment; filename=error.jpg'
            return response 
    except:
        print "Exception in user code:"
        print '-'*60
        traceback.print_exc(file=sys.stdout)
        print '-'*60
        errorImageData= getImageError()
        # send the file
        response = HttpResponse(errorImageData, content_type= 'image/jpg')
        response['Content-Length'] = fpInMemory.tell() if fpInMemory else None
        response['Content-Disposition'] = 'attachment; filename=error.jpg'
        return response         
예제 #7
0
def ajaxGetGrid(request):
    if not request.user.is_authenticated():
        return redirect_to(request, '/auth/login/')
    user1= request.user
    
    #####view mode values########################################################################
    # all: show the concerns/alternatives and ratings/weights                                   #
    # ac: show only alternatives and concerns (only works with write mode read)                 #
    #############################################################################################
    
    #####write mode values#######################################
    # read: can only see the values                             #
    # write: can see and change the values                      #
    #############################################################
    
    #####check table values#######################################
    # true: will call the javascript function isTableSaved()     #
    # false: will not call the javascript function isTableSaved()#
    ##############################################################
    
    checkForTableIsSave= False
    changeRatingsWeights= False
    changeCornAlt= False
    showRatingWhileFalseChangeRatingsWeights= True
    error= None;
    
    #validate the options
    gridUSID = None
    viewMode = None
    writeMode = None
    try:
        gridUSID= request.REQUEST['gridUSID']
        viewMode= request.REQUEST['viewMode']
        writeMode= request.REQUEST['writeMode']
    except KeyError:
        error = 'Invalid arguments.'
    
    #variable check
    try:
        if not gridUSID:
            error= 'name of the grid was not specified'
        if not viewMode:
            viewMode= 'all'
        if not writeMode:
            writeMode= 'write'
            
        if writeMode == 'write':
            changeCornAlt= True
            changeRatingsWeights= True
            if viewMode == 'ac':
                showRatingWhileFalseChangeRatingsWeights= False
        
        if request.REQUEST.has_key('checkTable'):
            if request.REQUEST['checkTable'] == 'true':
                checkForTableIsSave= True
    except:
        print "Exception in user code:"
        print '-'*60
        traceback.print_exc(file=sys.stdout)
        print '-'*60
        error= 'one or more variables were not found'
    
    if not error:
        # create the table for the template
        grids= user1.grid_set
        gridObj= grids.filter(usid= gridUSID) #gridObj is first a list 
        if len(gridObj) > 0:
            gridObj= gridObj[0]
            try:
                templateData= GridTableData(generateGridTable(gridObj))
                templateData.tableId= randomStringGenerator()
                templateData.changeRatingsWeights= changeRatingsWeights
                templateData.changeCornAlt= changeCornAlt
                templateData.showRatingWhileFalseChangeRatingsWeights= showRatingWhileFalseChangeRatingsWeights
                templateData.checkForTableIsSave= checkForTableIsSave
                #dic= __generateGridTable__(gridObj)
                template= loader.get_template('gridMng/gridTable.html')
                context= RequestContext(request, {'data': templateData})
                htmlData= template.render(context)
                return HttpResponse(createXmlSuccessResponse(htmlData), content_type='application/xml')
                #return render_to_response('gridMng/gridTable.html', {'table' : table, 'tableHeader': header, 'hiddenFields': hidden, 'weights':concernWeights, 'showRatings':showRatings, 'readOnly':readOnly, 'checkForTableIsSave':checkForTableIsSave }, context_instance=RequestContext(request))
            except:
                print "Exception in user code:"
                print '-'*60
                traceback.print_exc(file=sys.stdout)
                print '-'*60
                return HttpResponse(createXmlErrorResponse('unknown error'), content_type='application/xml')                
        else:
            return HttpResponse(createXmlErrorResponse('Grid was not found'), content_type='application/xml')
    else:
        return HttpResponse(createXmlErrorResponse(error), content_type='application/xml')