Tag: Tips

Students can buy Windows 7 upgrade for $30!

If you are a student then you should definitely check this out. Microsoft has a special for students where you can get Windows 7 upgrade for $30. The normal upgrade price for Windows 7 is about $129 right now. Windows 7 is definitely a worth upgrade for laptops. So, get it if you are student! 🙂

By the way, you might also have access to the MSDNAA program, which has Windows 7 Professional available for free. You can check if your school and program is participating by searching on the MSDN school search page.

Customizing the admin site listing for the standard Django User model

Django’s admin site is a great tool throughout development. Django also provides an authentication module that also reduces the development time. The problem is that the auth module predefines the admin classes that shows a very simplistic listing in the admin view.

By default this is how the admin view looks for the User model.

It is not easy to see how you can customize this. But if you read through django.contrib.admin.sites then the answers becomes clearer. You can unregister the existing class for the User model and register your own version. Below is what this translates to, put this code in one of your application’s admin.py (if you are calling admin.autodiscover in urls.py) or models.py files.

Read full post...

Setting up a development MySQL django user

Django creates a new test database every time you run the test cases, so I was wondering how I should setup the dev MySQL user so it can recreate the database without allowing this user to create or drop other databases.

Well, the answer was simple with MySQL since it doesn’t verify that the database exists before granting permissions on it. This resulted in the very convenient few statements below.

GRANT CREATE ON test_db_name.* TO dev_user@localhost;
GRANT ALL PRIVILEGES ON test_db_name.* TO dev_user@localhost;
FLUSH PRIVILEGES;

With these the dev_user can recreate this database as necessary. Have fun testing your applications 🙂

Syntax error in prototype when using evalScripts?

Here is a very technical entry. Are you getting syntax error when using prototype with IE to load HTML? In prototype 1.6.0.3 the error happens on line 604.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var Enumerable = {
  each: function(iterator, context) {
    var index = 0;
    try {
      this._each(function(value) {
        iterator.call(context, value, index++);
      });
    } catch (e) {         /////// <---- IE complains of syntax error on this line
      if (e != $break) throw e;
    }
    return this;
  },

The error is misleading and it took me a little time to figure this one out. Basically, this happens when you load HTML from server using AJAX and have prototype evalScripts, and the content being loaded has javascript encapsulated in an HTML comment.

1
2
3
4
5
<script type="text/javascript">
<!--
alert("The comment tags are the problem.");
// -->
</script>

Removing the HTML comment tags should resolve this syntax error. You can read more in this ticket.

Quick tip: Opening last window in Chrome

My main browser is Firefox, but I like Chrome’s short startup time and general javascript speed. Here is a useful tip if you use Chrome. Chrome doesn’t ask for confirmation if you close a window with multiple tabs. Don’t worry, it is very easy to bring those back. To bring the last session press CTRL+SHIFT+T simultaneously and your last window will popup.

This is also true across sessions, i.e. if you completely close Chrome or after you restart. In these cases open a new Chrome window, then press this combination and you will get another window with your last set of tabs.

Performance difference between varchar and text in PostgreSQL

I am one of the people that does read the documentation. My business partner, Jake, asked why use varchar with an artificial limit for fields that don’t really have a limit. My initial thought was because of performance benefits, but I had never verified this. So, I spent a few minutes to verify this and guess what I find in the PostgreSQL documentation.

… If you desire to store long strings with no specific upper limit, use text or character varying without a length specifier, rather than making up an arbitrary length limit.)

It continues on and says…

Tip: There are no performance differences between these three types, apart from increased storage size when using the blank-padded type, and a few extra cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, it has no such advantages in PostgreSQL. In most situations text or character varying should be used instead.

Exactly what I was looking for! This is what I call great documentation.

I have used MySQL in the past, but my experience with PostgreSQL has been awesome. Great database that scales relatively well (we will find that out soon :)), supports most of what you expect from a db, and has good documentation!

Adding * to required fields

Django’s forms (previously knows as newforms) framework has a lot cool functionality including the ability to output label tags. So, instead of typing the complete label and setting the correct for, you can just do form.field_name.label_tag and everything else is taken care of for you. The only problem is that there is no easy, documented way of adding an indicator (e.g. *) for required fields. One way would be to do if’s on each field and manually add an asterisk in the template, but that’s not DRY. After some search a few weeks ago I found an interesting post by Adil Saleem that showed one way of easily accomplishing this without changing all of your templates.

I really liked Adil’s solution, but I also wanted to change the class on the label so I could make those fields stand out (through CSS), and I also realized that he was really creating a python decorator, but in a weird way. So, here is a revised version of his solution with a slightly different approach (overriding label_tag instead of __init__) that adds the required field indicator and specifies a special CSS class (“required”) through a python decorator.

First we define two functions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.utils.html import escape

def add_required_label_tag(original_function):
  """Adds the 'required' CSS class and an asterisks to required field labels."""
  def required_label_tag(self, contents=None, attrs=None):
    contents = contents or escape(self.label)
    if self.field.required:
      if not self.label.endswith(" *"):
        self.label += " *"
        contents += " *"
      attrs = {'class': 'required'}
    return original_function(self, contents, attrs)
  return required_label_tag

def decorate_bound_field():
  from django.forms.forms import BoundField
  BoundField.label_tag = add_required_label_tag(BoundField.label_tag)

The first function is a decorator that provides the functionality and the second function assigns this decorator to BoundField.label_tag. The second function is really a helper function that allows you to easily add this to all your form modules.

Add the above code to one of your library files (maybe project.forms.__init__.py) and then in the module that defines your forms add the following code.

1
2
from project.forms import decorate_bound_field
decorate_bound_field()

Other than this you need to define the “required” CSS class.

1
label.required { font-weight: bold; }

Refresh your page with the form and all of your required fields will have an asterisk and the labels will be bold. Credit goes to Adil Saleem for coming up with the initial version, this is just a refinement 🙂

Change Ubuntu repository

The default Ubuntu repository is very busy and sometimes slow, especially around releases. So, one of the first things that I generally do after installing Ubuntu is change the repository to one that is generally more responsive. Synaptics has a nice features which it tests which repository might be best in your case, use that to figure out which one to use. In my case the MIT repository mostly seems to be very snappy. Below are the steps to changing the repository. Fortunately, it is all point-and-click.

1. Open Synaptic Package Manager (Ubuntu menu > System > Administration > Synaptic Package Manager).
2. Go to Settings menu, then “Repositories”

Choose "Repositories"

3. Under the first tab “Ubuntu Software” open the “Download from:” drop down and select other.

Choose "Other" from "Download from"

4. Here you have two options, first let Synaptic figure out the best server by clicking “Select Best Server” or pick one that I know generally works pretty good in US, the MIT repository (Under “United States” choose ubuntu.media.mit.edu).

Choose the MIT repository under "United States"

5. Click “Choose Server” and then close.
6. Now reload the repository and enjoy the faster download speeds 🙂

svn status -u

This is a very useful command if you are using subversion for version tracking. I just found out about the -u flag last week and I am loving it. It tells you exactly how an svn update would affect your working copy. This way you can decide whether you want to update to trunk with confidence. Previously there were times when I would update to the latest version only to realize that merging my code would take a little time, now I run this beforehand and decide whether to proceed right now or wait till I have more time. Enjoy 🙂

Pleasant surprise

Lately I have been playing around with Minefield (i.e. the development of firefox 3.1) with all its goodness of just in time (JIT) Javascript feature. Today I was browsing through its source code viewer and noticed something different. The JavaScript, CSS and other includes were actually links! How nice! 🙂 Now you don’t have figure out whether something is coming from the root or some other intertwined directory, just click and you are good to go. You can even drag and drop image reference to a tab and it will load from the correct location.

Take a look at the screenshot below to see for yourself 🙂

Firefox 3.1's source code viewer