change the default formating of the DateField in django forms Feb
23
1
1

Django forms are great, but sometimes you need to do a little work to get things just the way you want. The DateField has an easy way to restrict how data is entered through the input_formats option; but unless if I'm missing something there's isn't a similar way to help you set how the field displays the date in the template.

The default way the forms.DateField is displayed is YYYY-MM-DD, which is typically not what you want to present to the users.

The easiest way I have found to change how the date field displays is to write a small custom form field that inherits from forms.DateField that overrides the widget.

It would look something like this:

from django import forms
from django.utils.translation import ugettext_lazy as _


class FormattedDateField(forms.DateField):
    widget = forms.DateInput(format='%m/%d/%Y')

    def __init__(self, *args, **kwargs):
        super(FormattedDateField, self).__init__(*args, **kwargs)
        self.input_formats = ('%m/%d/%Y',)


class ProfileForm(forms.Form):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    birthday = FormattedDateField()

Or for a short-hand version that doesn't require overriding the form class could look something like the following:

class ProfileForm(forms.Form):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    birthday = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y')), input_formats=('%m/%d/%Y',))

Now, when I initialize the birthday field in the form instead of displaying YYYY-MM-DD, it will look like MM/DD/YYYY which is more natural to an American audience.

comments

extracting key value pairs of an array in javascript with jquery Jan
06
1
1

At times I feel spoiled using Python, especially when I try to do what seems to be a trivial operation to discover there's not already a construct to do it in whatever language I'm in at the time. One of these instances is when I try to loop over and extract key value pairs out of an array in Javascript. Being in the Python mode I'm usually hoping to find something like the following:

# python
for key, value in array:
    ....

The best I could come up with is to use the each() function from JQuery to loop over each element.

var example = {};

example['apple'] = 1;
example['orange'] = 2;

$.each(example, function(key, value) {
    console.log(key);
    console.log(value);
});

Or, for a non-jquery solution:

for(var key in example) {
    console.log(key);
    console.log(example[key]);
}

comments

how to stop / terminate / exit a python script Jan
03
1
1

I know this could be trivial to some of you, but it wasn't obvious to me which is why I'm posting. From time to time you might want to hard exit out of your python script. For me this came about when I was writing some system deploy and maintenance scripts. Just returning out of a function wasn't good enough because the rest of the script would keep on trucking. I needed to stop all execution of the script right there before it continued on and did irreversible damage to the system.

This can be done through the sys module.

import sys
sys.exit()

It's good to note that all this does is throws a SystemExit exception which can be caught like any other exception.

Alternatively you can use the os._exit() function which terminates at the C level and does not let the interpreter perform any of the normal tear-down procedures. It is not recommended to use os._exit() as sys.exit() should suffice for the vast majority of cases and is the recommended method.

comments

convert png to windows icon .ico file for favicon in ubuntu Dec
21
1
0

I've never had a great way of making windows icon files (.ico). I used to use the icon editor in Visual Studio in the past, but I haven't programmed in Windows for years and I don't have access to VS anymore. I've always felt there had to be a way to convert a png to ico file. Even Photoshop doesn't have this built in: for that you need a plugin.

It took me a while, but there's a way to do it using some of the packages from netpbm. If you're using Ubuntu you're in luck, as with most things it's just an apt-get away.

sudo apt-get install netpbm

Next, I'll start with a 16x16, 32x32 or 48x48 square pixel PNG. I tend to use the 32x32 size.

For this example I start with a 32x32 favicon.png, convert it to an intermediary pnm file, force the scaling to a ppm file, convert to 256 color space, and compile it into an ico file with the following set of commands.

pngtopnm -mix favicon.png > tmp_favicon.pnm

pnmscale -xsize=32 -ysize=32 tmp_favicon.pnm > tmp_favicon32.ppm
pnmscale -xsize=16 -ysize=16 tmp_favicon.pnm > tmp_favicon16.ppm

pnmquant 256 tmp_favicon32.ppm > tmp_favicon32x32.ppm
pnmquant 256 tmp_favicon16.ppm > tmp_favicon16x16.ppm

ppmtowinicon -output favicon.ico tmp_favicon16x16.ppm tmp_favicon32x32.ppm
rm -f tmp_favicon*

This method gave me what I needed: an ico file that I could use for a favicon and include as a windows icon for a binary executable.

comments

getting parent path of current directory in python Dec
10
1
0

The following code extracts the parent path of your current working directory, or any path value, in Python. I'm not sure if there's a way to automatically walk up and down through the directories, but this worked for me and was nice and small.

It works by splitting the path on "/", removes the last element in the array, then joins everything back together.

import os

path = os.getcwd()
parent_path = os.sep.join(path.split(os.sep)[:-1])

comments

custom user profile and extending the user admin in django Dec
08
1
0

In almost every project I do these days I need to extend and add fields to the default Django User model to store things like profiles, preferences, history etc.... One way to do this is to create a new model that inherits off of the django User class and use that class for authentication. This is usually not the best idea. In my case it got complicated integrating this change back into third party applications even when setting the AUTH_PROFILE_MODULE and writing a custom authentication backend.

The method I have been using lately works off a custom Model that links back to the User through a OneToOneField: based off the docs this is the recommended way to extend the django user. I find this method much cleaner to work with, and ultimately more compatible and maintainable. For instance I can work in my additions to the User in parallel with other applications. This is not possible if we are all inheriting off the User.

One of the main arguments that I hear against using a OneToOneField over Inheritance is that it creates extra database calls. This is not true. Perhaps a little known fact is that django implements model inheritance through a one-to-one relation: accessing fields from the subclass will do a query and accessing fields from the parent will do another query, so you're doing the same amount of queries either way. It's been mentioned that sub-classing models is not the right solution in most cases.

The following technique is not specific to extending just the User. This is a way to add additional attributes to an existing model written anywhere else in the project without having to modify the original source code. You can then make the additions show up in the admin by registering a custom extended ModelAdmin. This is essentially the same way I add additional properties to Satchmo products for e-commerce shops, although there are additional steps I need to take that are specific to Satchmo.

For this example lets do something simple, lets say something like adding a user profile for a blog that gives me the ability to create an avatar and a biography description for each user.

I'll first start out by defining a custom profile model class that'll attach the desired fields to the django user model.

I want to create this model whenever a user is created so I'll also add a profile creation method to the post_save signal for the User model.

# models.py
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField(upload_to='uploads/avatars', default='', blank=True)
    biography = models.TextField(default='', blank=True)

    def __unicode__(self):
        return self.user.username


def create_user_profile(sender, instance, created, **kwargs):
    """Create the UserProfile when a new User is saved"""
    if created:
        profile = UserProfile()
        profile.user = instance
        profile.save()

post_save.connect(create_user_profile, sender=User)

This is a great start. The above code will provide me the ability to add additional fields to the django user with minimal intervention. This might be all I actually need, but I like to push things further; and in this case it's a good idea to make the user profile available in the admin.

Although I could have the admin autodiscover the model like usual, I find it much more efficient to inline the UserProfile into the existing User admin view. To do this I create an inline for the new profile and add it to a custom UserAdmin class that inherits off of the django UserAdmin class.

The process of replacing an existing registered model admin is easy, you just need to remember to unregister the model first. This gives me the ability to adjust the default django user admin view without having to modify any core code.

# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

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


class ProfileInline(admin.StackedInline):
    model = UserProfile
    fk_name = 'user'
    max_num = 1


class CustomUserAdmin(UserAdmin):
    inlines = [ProfileInline,]


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

An optional step is to can add AUTH_PROFILE_MODULE in settings.py. I tend NOT to do this because other applications that I integrate, like Satchmo, already have this field set and I don't want step on anyone's toes.

Lets say I put models.py and admin.py in an application named 'custom'.

# settings.py
AUTH_PROFILE_MODULE = 'custom.UserProfile'

This setting allows me to pull the profile off of the django user with the get_profile() method.

profile = user.get_profile()

It's handy but not necessary. You can always get the profile the old-fashioned way:

profile = user.userprofile

I hope this explanation helps. I'm jotting it down mainly so I can refer back to it later as I tend to forget where things are located and what I need to include. There could be a better way to do things, but this has worked for me and hopefully it'll be helpful for someone else. As always feedback and comments are welcome.

Happy coding!

comments

stupid simple web server with python Dec
08
1
0

If you need to set up a basic web server really fast and you don't want to go through the hassle of setting up nginx, apache or another production-level web server you can just use Python. If you're lucky like me you're already developing in it anyway.

Python comes with a simple web server built in: SimpleHTTPServer

All you need to do is to change to the directory you want to host and call it:

cd /path/to/directory
python -m SimpleHTTPServer

That's all there is to it. You'll then be serving rooted to that directory. You can access it through localhost, 127.0.0.1, or your inet IP.

It will look for and automatically host index.html. If index.html isn't found then it will list the contents of the directory specified.

http://localhost:8000
http://192.168.1.###:8000

The default port is 8000, but you can easily change it. One things I use this for is when I need to initiate more than one simple server at once.

python -m SimpleHTTPServer 8080

Keep in mind that this is a single threaded server and it breaks easily. This most definitely should NOT be used in production.

Among other things this an easy way to transfer files between computers through your local network using only Python.

reference: http://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python

comments

git-aware ps1 Nov
19
1
0

http://blog.bitfluent.com/post/27983389/git-utilities-you-cant-live-without

You'll need git-completion.bash working, but put the following line into your .bashrc or .bash_profile to display the current branch in your terminal.

PS1='$(__git_ps1 "(%s)")$ '

Which you can combine with whatever you already have setup. It can be something similar to one of the following:

PS1='\h:\W$(__git_ps1 "(%s)") \u\$ '
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\ $(__git_ps1 "(%s)")$ '
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] $(__git_ps1 "(%s)")$ '

comments

installing a lamp stack on ubuntu Nov
17
1
0

If you're ever in the unfortunate position where you need to install a LAMP stack (Linux, Apache, MySQL, PHP) on an Ubuntu server, you can install the following modules to quickly get yourself up and running.

apache2 php5-mysql libapache2-mod-php5 mysql-server

sudo apt-get install apache2
sudo apt-get install php5-mysql
sudo apt-get install libapache2-mod-php5
sudo apt-get install mysql-server

Or, for the super lazy use tasksel:

sudo tasksel install lamp-server

Good luck and godspeed.

comments

random string and digit generation in python Nov
17
1
0

This snippet generates a random string with digits with a defined LENGTH in Python. Useful for things like generating random passwords.

import os
import string


LENGTH = 6

password = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(LENGTH))

comments