Posts Tagged ‘Django’

Django forms method GET and POST

November 19th, 2008

As mentioned in my last entry on ModelForms, i was playing around with ModelForms in Django. I found something interesting in using both the get and post method.

I have 2 pages – one for forms. the other is to confirm values / pay. However, based on the last entry, I didnt really want to save the values in the form after i click submit.

to retract how the form looks like, here is it below:

def sample(request):
if request.method == “POST”:
form = SampleForm(request.POST)
if form.is_valid():
new_Sample = form.save(commit=False)
new_Sample.label = ‘Sample01′
new_Sample.save()
return HttpResponseRedirect(’/contact/thanks/’)
else:
print “no sell request”
form = SampleForm()
return render_to_response(’Sample.htm’, {’form’: form})

So, in order to change it to 2 pages. i changed the form page so it goes to the next page.

<form action=”sample2” method=”GET”>
<dl>
<dt><label for=”id_user”>user:</label>{% if user.errors %} <span class=”error”>{{ user.errors|join:”, ” }}</span>{% endif %}</dt>
<dd><input type=”text” name=”user” value=”{{ user }}” size=”6″></dd>
<dt><label for=”id_number”>number:</label>{% if number.errors %} <span class=”error”>{{ number.errors|join:”, ” }}</span>{% endif %}</dt>
<dd>  <input type=”text” name=”number” value=”{{ number  }}” size=”6″></dd>
<dt><input type=”submit” value=”Submit” /></dt>

and the views is a simple printing of form

def sample(request):
print “no sell request”
form = SampleForm()
return render_to_response(’Sample.htm’, {’form’: form})

Thus, when click on the button submit: it goes to the next page where all the values in the form is sent there. the url should show something like localhost:8000/sample2/?user=weiyang&number=10

and then for sample 2

def sample2(request):
if request.method == “POST”:
form = SampleForm(request.POST)
if form.is_valid():
new_Sample = form.save(commit=False)
new_Sample.label = ‘Sample01′
new_Sample.save()
return HttpResponseRedirect(’/contact/thanks/’)
else:
print “no sell request”
form = SampleForm()
return render_to_response(’Sample2.htm’, {’form’: form})

and my sample2.htm is shown as

<form action=”.” method=”POST”>

<input type=”hidden” size=”10″ name=”user” value=”{{ user }}”  />
<input type=”hidden” size=”10″ name=”number” value=”{{ number }}”  />
…..posting of values to be seen….

</form>

hope this helps.

VN:F [1.9.6_1107]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
DiggTwitterTechnorati FavoritesRedditNewsVineFacebookShare

ModelForms in Django

November 13th, 2008

I was supposed to create a form for entry into the database and I found a simple ModelForms way as listed in the Django documents.

I made use of 4 files – forms.py, models.py, views.py and the html

1. Starting off with models.py and database is assume to be validated and syncdb is used to create the db.

from django.db import models
from django.contrib.auth.models import User

Class Sample (models.Model):

user = models.ForeignKey(User)

number  = models.FloatField()

label = models.CharField(max_length=30)

2. Once Db is setup properly, forms.py is setup

from django import newforms as forms

from models import Sample
from django.forms import ModelForm

Class SampleForm(ModelForm):

class Meta:
model = Sample
fields = (‘number’, ‘user’ )

Thus, in here, the forms will make use of the models.py and those fields indicated will be popluted in the Form

3. Next, We setup the views.py

def sample(request):
if request.method == “POST”:
form = SampleForm(request.POST)
if form.is_valid():
new_Sample = form.save(commit=False)
new_Sample.label = ‘Sample01′
new_Sample.save()
return HttpResponseRedirect(‘/contact/thanks/’)
else:
print “no sell request”
form = SampleForm()
return render_to_response(‘Sample.htm’, {‘form’: form})

Urls.py is assumed to setup properly.

4. and lastly, the sample.htm is done

<form action=”.” method=”POST”>
<dl>
<dt><label for=”id_user”>user:</label>{% if user.errors %} <span class=”error”>{{ user.errors|join:”, ” }}</span>{% endif %}</dt>
<dd><input type=”text” name=”user” value=”{{ user }}” size=”6″></dd>
<dt><label for=”id_number”>number:</label>{% if number.errors %} <span class=”error”>{{ number.errors|join:”, ” }}</span>{% endif %}</dt>
<dd>  <input type=”text” name=”number” value=”{{ number  }}” size=”6″></dd>
<dt><input type=”submit” value=”Submit” /></dt>

and done.. thats all you need to do to create a form in Django using database and some manipulation.

VN:F [1.9.6_1107]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
DiggTwitterTechnorati FavoritesRedditNewsVineFacebookShare

Paypal with Django

November 5th, 2008

I am currently writing an django application that requires simple encrypted paypal transactions. Just a simple pay and transfer transactions. I found a couple of modules for paypal (e.g. django-cart, pypaypal). However, I was just looking for a simple and easy way to do the transactions (e.g. snippets, blogs). I found Jon Atkinson’s blog pretty useful.

First off,  you created a public key to upload to paypal certificate. This is done using openssl. Windows users are require to download and install openssl in order to create the key. Thereafter, create your private key as shown:

$ openssl genrsa -out my-prvkey.pem 1024

and public key as shown below:

$ openssl req -new -key my-prvkey.pem -x509 -days 365 -out my-pubcert.pem

Next, obtain a paypal certificate by uploading your public key – my-pubcert.pem.
If you dunt have a paypal account or if this is just for testing, paypal sandbox could be a useful tool. Create 2 test accounts – personal and business. Enter into your paypal test site for your business account. Click on
=> profile (under My Account)
=> Encrypted Payment Settings (under selling preferences)
=> Click “Add” button (under Your Public Certificates)
=> browse and upload your public key – my-pubcert.pem.
=> go back to the Website Payment Certificates
=> Click “Download” button under Paypal Public Certificate

So now, there are three files that are needed to be place in your django project folder – paypal_cert.pem, my-pubcert.pem and my-prvkey.pem. Edit the Settings.py accordingly
MY_KEYPAIR = ‘/path/to/certs/my-prvkey.pem’
MY_CERT = ‘/path/to/certs/my-pubcert.pem’
PAYPAL_CERT = ‘/path/to/certs/paypal_cert.pem’
MY_CERT_ID = ‘AAAAAAAAAA’ <12 letters / numbers – found under Cert ID in Website Payment Certificates after uploading your public key>

Next up create a paypal.py file for reference.

from M2Crypto import BIO, SMIME, X509
from django.conf import settings

def paypal_encrypt(attributes):

plaintext = ”

for key, value in attributes.items():
plaintext += u’%s=%s\n’ % (key, value)

plaintext = plaintext.encode(‘utf-8′)

# Instantiate an SMIME object.
s = SMIME.SMIME()

# Load signer’s key and cert. Sign the buffer.
s.load_key_bio(BIO.openfile(settings.MY_KEYPAIR), BIO.openfile(settings.MY_CERT))

p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)

# Load target cert to encrypt the signed message to.
x509 = X509.load_cert_bio(BIO.openfile(settings.PAYPAL_CERT))
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)

# Set cipher: 3-key triple-DES in CBC mode.
s.set_cipher(SMIME.Cipher(‘des_ede3_cbc’))

# Create a temporary buffer.
tmp = BIO.MemoryBuffer()

# Write the signed message into the temporary buffer.
p7.write_der(tmp)

# Encrypt the temporary buffer.
p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)

# Output p7 in mail-friendly format.
out = BIO.MemoryBuffer()
p7.write(out)

return out.read()

For encryption, we will use the M2Crypto (module can be downloaded here).

I tried using 0.19 but it gave me some problems. Thus, i used M2Crypto-0.18.2 and it works.

Insert the following code into your application views.py

def pay(request, invoice_id):
“”"This view displays an encrypted PayPal ‘buy now’ button”"”
invoice = get_object_or_404(Transaction, id = 1)

attributes = {}
attributes['cmd'] = ‘_xclick’
attributes['business'] = ‘weiyan_122234560_biz@hotmail.com’
attributes['item_name'] = invoice.item_name  #invoice.item_name
attributes['amount'] = invoice.amount #invoice.amount
attributes['currency_code'] = ‘USD’

encrypted_block = paypal_encrypt(attributes)
#encrypted_block = attributes
return render_to_response(‘pay.html’,
{‘item_name’: invoice.item_name,
‘encrypted_block’: encrypted_block,
‘amount’: invoice.amount,
‘attributes’: attributes,
})

Take Note: for the attributes['business'], it should be the name of your paypal account.

Next, create your pay.html (form page)
a simple example is shown below

<body>
invoice item_name: {{ item_name }}<br/>
invoice amount: {{ amount }}<br/>
attributes: {{ attributes }}<br/>
encrypted_block: {{ encrypted_block }}

<form action=”https://www.sandbox.paypal.com/cgi-bin/webscr” method=”post”> <input name=”cmd” type=”hidden” value=”_s-xclick” />
<input name=”encrypted” type=”hidden” value=”{{ encrypted_block }}” />
<input class=”button pay” name=”submit” type=”submit” value=”Pay Invoice” />
</form>

And you have successfully integrated your paypal transactions with your Django project

VN:F [1.9.6_1107]
Rating: 9.0/10 (1 vote cast)
VN:F [1.9.6_1107]
Rating: +1 (from 1 vote)
DiggTwitterTechnorati FavoritesRedditNewsVineFacebookShare
Get Adobe Flash playerPlugin by wpburn.com wordpress themes