Java Jester

Saturday, October 18, 2008

Ternary Operator in Python Does not Make Sense

I don't know why python did'nt simply followed the standard way of using a ternary operator. Instead of following the usual format:

(x > 10) ? true_value : false_value

Python uses a different one:

x > 10 and true_value or false_value

 

Saturday, October 18, 2008

Unit Testing Django Component Example

At the moment I dont know how to test django components from eclipse so I'm running my test on the terminal window. To test your django components, create a tests.py file on your application folder. For example my myapp/tests.py looks like the following:


from myapp.models import *
from myapp.forms import *
from mypp import log
import unittest


class CountryTestCase(unittest.TestCase):
    """
    Test case for country model
    """
    
    def setUp(self):
        log.debug('Running CountryTestCase')
      
    def testCountCountries(self):
        allquery = Country.objects.all()
        self.assertTrue(allquery.count() > 0)
       
       
class RegistrationTestCase(unittest.TestCase):
    """
    Test case for user registration
    """
   
    def setUp(self):
        user = User(email='reyjexter@gmail.com', username='reyjexter@gmail.com', is_superuser=0,is_staff=0, is_active=1)
        user.save()
       
        user = User(email='core_reyj@yahoo.com', username='core_reyj@yahoo.com', is_superuser=0,is_staff=0, is_active=0)
        user.save()  
       
    def tearDown(self):
        userquery = User.objects.all()
        for user in userquery:
            user.delete()
       
    def testFailedRegistration(self):
        postdata = {
            'email': 'reyjexter@gmail.com',
            'password': 'rey123',
            'confirm_password': 'rey123',           
        }
        form = UserRegistrationForm(postdata)
        self.assertFalse(form.is_valid())
       
        postdata = {
            'email': '',
            'password': 'rey123',
            'confirm_password': 'rey123',           
        }
        form = UserRegistrationForm(postdata)
        self.assertFalse(form.is_valid())
       
        postdata = {
            'email': 'rey@ideyatech.com',
            'password': 'rey123',
            'confirm_password': 'rey1234',           
        }
        form = UserRegistrationForm(postdata)
        self.assertFalse(form.is_valid())
       
    def testSuccessRegistration(self):
        postdata = {
            'email': 'rey@ideyatech.com',
            'password': 'rey123',
            'confirm_password': 'rey123',           
        }
        form = UserRegistrationForm(postdata)
        self.assertTrue(form.is_valid())
       
        countBeforeInsert = User.objects.all().count()
        form.save()
        self.assertTrue(User.objects.all().count() == countBeforeInsert+1)
        

To execute the test simple run:

./manage.py test myapp

Or to run individual test, run this one:

./manage.py test myapp.RegistrationTestCase

 

Friday, August 15, 2008

Sending email using gmail smtp

It was amazing that the django framework included an easy way to integrate email sending using gmail smtp. I simply added the following code on my setttings.py and the email is sent using gmail smtp:

# use gmail smtp
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'mygmailaccount@gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword123'
EMAIL_PORT = 587

 

Wednesday, August 13, 2008

Elegant custom validation in django

At the time of this writing, the official django documentation doesn't teach an elegant way to handle custom form validation. After digging the django source code for a couple of minutes, I learned that I can place custom field validation on form class by defining a method named 'clean_<field_name>(self)'. In my example below, I'm adding custom fields that need to be validated against the database because I don't want any registration using the same email address. The following code shows how to do this:



class RegistrationForm(forms.ModelForm):

gender = forms.ChoiceField(required=True, widget=forms.RadioSelect, choices=GENDER)
    agree_to_terms = forms.BooleanField(required=True, help_text='You must agree to terms and conditions') 
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True, widget=forms.PasswordInput())
    password2 = forms.CharField(required=True, label='Re-enter password')

def clean_email(self):
    email = self.cleaned_data["email"]
    try:
        User.objects.get(email=email)
    except
        User.DoesNotExist: return email raise forms.ValidationError('This email address is already taken.')

def clean_password2(self):
    password = self.cleaned_data["password"]
    password2 = self.cleaned_data["password2"]
    if password == password2:
        return password2
    raise forms.ValidationError('Confirmation password should be equal to the password')

class Meta:
    model = UserProfile
    exclude = ('user', 'is_activated', 'activation_key', )

 

Wednesday, July 23, 2008

Django 1.0 alpha released!

2 days ago, django 1.0 alpha was released. I immediatly upgraded to the latest version on svn trunk but got disappointed because my site was not working properly. The admin site is broken so I needed to do a little research. There were serious number of changes that was made specifically on the admin site. This documentation guided me in fixing my blog site:

http://www.djangoproject.com/documentation/release_notes_1.0_alpha/

After I finished applying all the changes from their documentation, I tried browsing the admin but I'm still getting an error message saying something like "TemplateSystaxError on /admin/". What I did is drop my database, re-run the "manage.py syncdb" and replace the overriden admin/base_site.html with the one on django contrib package and the error message went away.

Fixing the problem was a bit difficult because at that time, the documentation was not yet up on django website. Maybe after the release of final v1.0 I'll stick to it and won't ever use django trunk version in production.

Anyway, congrats to django team for releasing version 1.0 alpha


 


recommended books
Jester Cap Logo by Vonn reyjexter.com | Valid XHTML & CSS | 2008 | Design & Devt. by: vonnhugo

powered by:

django framework python google app engine