Image Cropping in Jquery(with Jcrop)

Many applications need to crop image that is being uploaded. For that there is a plugin called Jcrop in jquery. It is very easy to use and understand. Here is a simple example to crop image using Jcrop.

Here is our simple image tag which we’ll crop.


<img src="pool.jpg" id="target" />

Download the latest version of JCrop.js and Jcrop.css and keep them in your html file as below.


<script src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />

Usage:
Initialise the Jcrop with the image tag as follows.


jQuery(function($) {
$('#target').Jcrop();
});

with the above step it will convert the image tag into a widget to crop the image.

Other attributes those are useful while converting the image tag into a widget:

1. aspectRatio: Aspect ratio of w/h (e.g. 1 for square) this will keep the aspect ratio for the selected area in the image.

2. onSelect: This will give the coordinates of the selected area like width, height, x-coordinate…etc.,

3. minSize, maxSize: These two will keep the minimum and maximum cropping sizes of the image respectively

4. onRelease: This is called when the selected area is released.

Share on Google+Share on FacebookTweet about this on TwitterShare on LinkedInShare on RedditEmail this to someone

E-commerce (paypal) integration with Django

E-commerce is integration is becoming almost essential for every web application now a days. There are so many payment gateways to integrate with our application. Some of them are Amazon payments, Asiapay, BPAY, Brain Tree, PayPal …etc. Out of these now in this we’ll see how to integrate Paypal with our django Application.

Integrating Paypal with Django:

Paypal provides two kinds of api for integrating any application with it. They are

1.PayPal REST api

2.PayPal CLASSIC api

1. Integrating with REST api:

Integrting paypal with dajngo with REST api is some what easy and easy to understnad. Paypal provides a sdk for integrating PayPal with Django, that is ‘paypal rest sdk’. For more about restsdk check this https://github.com/paypal/rest-api-sdk-python

and https://developer.paypal.com/webapps/developer/docs/api/

2.Integrating Paypal with classic api:

First intialise the paypal urls for endpoint and paypal connection as follows.

End_url = ‘https://api-3t.sandbox.paypal.com/nvp’
PAYPAL_URL = ‘https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=’

Buyers use Express Checkout to pay you on PayPal’s secure site and return to your site to complete the transaction.

1.Setting express checkout for transaction:

params = {
'USER' : 'xxxxxxxx', # Edit this to your API user name
'PWD' : 'xxxxxxxx', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
'METHOD':'SetExpressCheckout',
'VERSION':86,
'PAYMENTREQUEST_0_PAYMENTACTION':'SALE',     # type of payment
'PAYMENTREQUEST_0_AMT':50,              # amount of transaction
'PAYMENTREQUEST_0_CURRENCYCODE':'USD',   
'cancelUrl':"xxxxxxxxxxxxx",    #For use if the consumer decides not to proceed with payment 
'returnUrl':"xxxxxxxxxxxx"   #For use if the consumer proceeds with payment
}

    params_string = urllib.urlencode(params)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read() #gets the response and parse it.
    response_dict = parse_qs(response)
    response_token = response_dict['TOKEN'][0]
    rurl = PAYPAL_URL+response_token #gather the response token and redirect to paypal to authorize the payment
    return HttpResponseRedirect(rurl)

2.Executing the express checkout payment

exparams = {
'USER' : 'xxxxxxx', # Edit this to your API user name
'PWD' : 'xxxxxx', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
'VERSION':86,               
    
'METHOD':'DoExpressCheckoutPayment',
'TOKEN':'xxxx', #get the token from the request that is redirected
'PAYERID':payerid,      # customer's unique PayPal ID
'PAYMENTREQUEST_0_PAYMENTACTION':'SALE',    # payment type
'PAYMENTREQUEST_0_AMT':50,             # transaction amount
'PAYMENTREQUEST_0_CURRENCYCODE':'USD'
}
      
    params_string = urllib.urlencode(exparams)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read()
    return HttpResponse(response)

In response you will get the following details

token,transactionid,receipientid, paymenttype, transaciontype…. etc., For more about the parameters to be sent and the response details please refer to https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoExpressCheckoutPayment_API_Operation_NVP/

3.Refunding the transaction:

params = {
'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 

'VERSION':86,
'METHOD':'RefundTransaction',
'TRANSACTIONID':'60Y29533L12153911',    #ID of the transaction for which the refund is made 
'REFUNDTYPE':'Full'   
}
    params_string = urllib.urlencode(params)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read()
    return HttpResponse(response)

Gather the transactionid from the payment created.The refund can be done in 4 ways. They are

Type of refund you are making. It is one of the following values:

  • Full – Full refund (default).
  • Partial – Partial refund.
  • ExternalDispute – External dispute. (Value available since version 82.0)
  • Other – Other type of refund. (Value available since version 82.0)

Creating Recurring Payment:

Using CLASSIC api we can create a recurring payment. A Recurring Payment Regularly scheduled payment of a consumer debt, such as an installment loan, which is payable monthly or yearly ..etc., 

For more about parameters to be sent and response details refer to https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/RefundTransaction_API_Operation_NVP/

1.Creating a Recurring Payment:

params = {
'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
'METHOD':'SetExpressCheckout',
'VERSION':86,
'L_BILLINGTYPE0':'RecurringPayments',    #The type of billing agreement
'L_BILLINGAGREEMENTDESCRIPTION0':'FitnessMembership',    #The description of the billing agreement
'cancelUrl':"http://localhost:8000/paycanret/",    #For use if the consumer decides not to proceed with payment 
'returnUrl':"http://localhost:8000/payauthret/"   #For use if the consumer proceeds with payment
}

    params_string = urllib.urlencode(params)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read()
    response_dict = parse_qs(response)
    response_token = response_dict['TOKEN'][0]
    rurl = PAYPAL_URL+response_token
    return HttpResponseRedirect(rurl)

2.Creating the profile after authentication:

    recparams = {
'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
'METHOD':'CreateRecurringPaymentsProfile',
'VERSION':86,
'TOKEN':request.GET.get('token'),
'PAYERID':payerid,
'PROFILESTARTDATE':datetime.datetime.now(),    #Billing date start, in UTC/GMT format
'DESC':'FitnessMembership',    #Profile description - same as billing agreement description
'BILLINGPERIOD':'Day',    #Period of time between billings
'BILLINGFREQUENCY':1,    #Frequency of charges 
'AMT':1,    #The amount the buyer will pay in a payment period
'CURRENCYCODE':'USD'    #The currency, e.g. US dollars
    

}
    
    
    
    params_string = urllib.urlencode(recparams)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read()
      
    return HttpResponse(response)

This will create the recurring payment profile and do the payment as the billing frequency and billing period you provided.

For more about parameters to be sent and response detials refer to

https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/

3.Cancelling the Recurring profile:

form_fields = {
        "METHOD": "ManageRecurringPaymentsProfileStatus",
        "PROFILEID": "I-GRYD2P8AL3UX", # put your subscription ID here
        "ACTION": "cancel",
        'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
        "VERSION": 86
}

    

    form_data = urllib.urlencode(form_fields)

    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', form_data).read()
    
    return HttpResponse(response)

get the profile id form the recurring payment that is created.

Doing the direct payment with out redirecting to the paypal account with the user card:

nvp_params = {
            # 3 Token Credentials
'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
        "VERSION": 86,

            # API Version and Operation

            'METHOD' : 'DoDirectPayment',

            # API specifics for DoDirectPayment
            'PAYMENTACTION' : 'Sale',
            'IPADDRESS' : client_address,
            'AMT' : '1',
            'CREDITCARDTYPE' : 'MasterCard',
            'ACCT' : '5490940605734691',
            'EXPDATE' : 112018,
            'CVV2' : '123',
        
            'FIRSTNAME' : 'chaitanya',
            'LASTNAME' : 'kattineni',
            'STREET' : '1 Main St',
            'CITY' : 'San Jose',
            'STATE' : 'CA',
            'ZIP' : '95131',
            'COUNTRYCODE' : 'US'
        }
    
    form_data = urllib.urlencode(nvp_params)

    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', form_data).read()
    
    return HttpResponse(response)

It will return the details regarding the transaction done. For more about parameters to be sent and response details refer to https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoDirectPayment_API_Operation_NVP/

 

Share on Google+Share on FacebookTweet about this on TwitterShare on LinkedInShare on RedditEmail this to someone

Dynamic Models in Django-Part1 (adding new fields to models from admin)

Some times in the production level there may be a chance of adding new fields to our model.With the normal django models when we add new field to the model the database is not able to identify the new field.To make database identify the new field we have to drop the existing database from the database and sync our application again.During the time of production it is not possible to remove the existing data.

The solution for this is Django-eav.With this we can add any no of fields to our models on fly.

Steps To add New fields to the models Using django-eav:

Step1:Install django-eav using the following command

pip install -e git+git://github.com/mvpdev/django-eav.git#egg=django-eav

Step2:Add ‘eav’ to your INSTALLED_APPS in your project’s settings.py file.

Step3:Register your models with eav.

To register any model with EAV, you simply need to add the registration line somewhere that will be executed when django starts:

import eav
eav.register(Patient)

Keep the above lines any where in your models.py

Step4:Configure your models so that you can create new fields from admin it self

You can even have your eav attributes show up just like normal fields in your models admin pages. Just register using the eav admin class:

from django.contrib import admin
from eav.forms import BaseDynamicEntityForm
from eav.admin import BaseEntityAdmin

class PatientAdminForm(BaseDynamicEntityForm):
    model = Patient

class PatientAdmin(BaseEntityAdmin):
    form = PatientAdminForm

admin.site.register(Patient, PatientAdmin)

After following all the above steps sync your project with database using

python manage.py syncdb

Run your project using

python manage.py runserver

command and go to your admin page and add new Attributes(fields) to the Existing model. There you can add new attributes to your model.

In Part-2 of This tutorial we’ll see how to add attributes programatically and detailed explanation of Attributes and Values.

Share on Google+Share on FacebookTweet about this on TwitterShare on LinkedInShare on RedditEmail this to someone

QRCode generation in python

What Is QRCode?
A Quick Response code is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of any kind of data (e.g., binary, alphanumeric, or Kanji symbols)

QRCode generation in Python:
Here are the simple steps to generate QRCode image in python

First install qrcode module in your system using the following command

pip install qrcode

Simple code to generate a QRcode image

import qrcode
img = qrcode.make('Some data here')

This above snippet will return a PIL image object, you can save that image where ever you can with what ever name you want.

img.save('/path/imagename.extension')

Some advanced code to generate QRCode image:

import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('Some data')
qr.make(fit=True)

img = qr.make_image()
img.save('/path/imagename.extension')

In the above code

The version parameter is an integer from 1 to 40 that controls the size of the QR Code (the smallest, version 1, is a 21×21 matrix). Set to None and use thefit parameter when making the code to determine this automatically.

The error_correction parameter controls the error correction used for the QR Code. The following four constants are made available on the qrcode package:

ERROR_CORRECT_L
About 7% or less errors can be corrected.
ERROR_CORRECT_M (default)
About 15% or less errors can be corrected.
ERROR_CORRECT_Q
About 25% or less errors can be corrected.
ERROR_CORRECT_H.
About 30% or less errors can be corrected.

The box_size parameter controls how many pixels each “box” of the QR code is.

The border parameter controls how many boxes thick the border should be (the default is 4, which is the minimum according to the specs).

Share on Google+Share on FacebookTweet about this on TwitterShare on LinkedInShare on RedditEmail this to someone

Python-reCaptcha

How to integrate reCaptcha with django?

Following gives you a brief idea of how to integrate reCaptcha to django application

  • First get the corresponding public key and private key from reCaptcha site and keep them in your settings.py
in settings.py
CAPTCHA_PUBLIC = 'XXXXXXXXXXXXXXXXXX'
CAPTCHA_PRIVATE = 'XXXXXXXXXXXXXXXXXX'
  • Render the reCaptcha to corresponding html page
in views.py
recaptcha = captcha.displayhtml(CAPTCHA_PUBLIC) 
    #displayhtml() gives the captcha object to be displayed on html
return render_to_response('demo.html','recaptcha':recaptcha)
in demo.html
<form action="/" method="post" >
{{recaptcha|safe}}
        <button class="submit" type="submit">Submit</button>
</form>
  • Validate the challenge field and response fields..
in views.py
capresponse = captcha.submit( request.POST.get('recaptcha_challenge_field'),
                              request.POST.get('recaptcha_response_field'),
                              CAPTCHA_PRIVATE,
                              request.META.get('REMOTE_ADDR'))
'''checks if the catpcha is valid or not(challenge field and response fields    are equal or not '''
if capresponse.is_valid:
     do_some_work()
else:
     return HttpResponse('wrong captcha text')
Share on Google+Share on FacebookTweet about this on TwitterShare on LinkedInShare on RedditEmail this to someone