Java Jester

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


 

Sunday, July 20, 2008

To google app engine or not?

Google app engine is probably one of the most interesting platforms that is offered today. It offers free web hosting and web application management platform.

I tried playing with google app engine for a couple of days. The process of development and managing the version of your web application is easy. They even offer a helper library so that some components of django can smoothly integrate with the platform. My first thought was google plus django will help aspiring software entrepreneur such as myself focus in developing application without having to worry about the hosting and instead concentrate on the application's functionality. This was half true because by using google app engine, I freed myself from worrying about the hosting, server configuration and deploying the application.

Things went harder when developing django application that will be deployed on google's platform. Google took away some of django's component such as the site admin, the user module, the security and the database api. Google provided an alternative called "Google App Engine Django Helper" so that django can easily integrate with google app engine. Unfortunately, It did'nt do the job and correct me if I'm wrong but I think it's buggy.

At the moment, I'll be developing purely using django framework and I'll host my projects somewhere else (This blog site by the way is hosted at djangohosting.ch which is a very affordable django hosting). But I do hope that in future, django will fully support google app engine's platform without having to do so much things and hopefully without having to use that google-jango helper library.

 


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