May 28, 2010

Django Contrib Revealed - Sites

Ok so the first element from django.contirbution I'm goin to write here about will be Sites package. What is Sites used for and what it's all about anyway ?
Let's say you have two sites connected together and sharing one database (i.e. community portal, and news site). You're using one login and authentication system there, one folder with uploaded pictures but different views for sites and different templates.
In settings file, community site has ID of 1 and news site's ID is equal to 2. How we would now build shared News model for both sites ?
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.sites.managers import currentSiteManager

class News(models.Model):
    title = models.CharField(max_length=100)
    # ...
    site = models.ForeignKey(Site)
    objects = models.Manager()
    current_site = CurrentSiteManager()
As we can see from the code, we must add a field related to Site model in our class declaration (in this example it is many-to-one relationship). We can also notice two managers. The default objects is well known to us. It just serves .objects.all() . And for the second one it's a built in manager for serving objects specific to each site. So now News.objects.all() gives us all news (for example to feeds), and News.current_site.all() will return only News from current site. One thing to remember is that if our site-related field has different name than 'site' in CurrentSiteManager we need to specify this handler :
current_site = CurrentSiteManager('site_related_field')
And now for the views :
from django.conf.import settings

def simple_view(request):
    if settings.SITE_ID == 1:
        # code here
        # code here
But as you can see it's not the cleanest solution. It would be better if we had current site stored somewhere for the future use. Also, there is no need for refering to settings each time, because every Site model has a method .get_current() :
from django.contrib.sites.models import Site

def simple_view(request):
    current_site = Site.objects.get_current()
    #here we're using one of Site models field - domain.
    if current_site.domain == '':
        #code here
        # code here
Just to finish things up. Other field of Site model is name (which returns name of current site). And if you still prefere to use settings instead of get_current method, here's the code for that :
from django.conf import settings
from django.contrib.sites.models import Site

def simple_view(request):
    current_site = Site.objects.get(id=settings.SITE_ID)
    #here we're using one of Site models field - domain.
    if == 1:
        #code here
        # code here

May 27, 2010

Parsing string

Yesterday I was checking my marks from C++ Programming subject (as it turned out, there's almost no chance I will pass it :/). Points from each lab are stored in spreadsheet, and when copied they looked like this :

"1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1"

Because exams are closing, I'm starting to get lazy. That's why instead of copying and summing all the values in google, I thought about using Python to parse through this string to get their sum. That's what I came up with :
#note using fsum to preserve float loss
fsum(float(n) for n in str.replace(',','.').split())
And here's second solution, since ',' is a legitimate decimal point for many people.
import locale
sum(map(locale.atof, s.split()))

May 26, 2010

Generic views part 1

Problem with start page of your web app is most common: "Do I need to create view for index.html, just to allow loading the page ?". Well you don't. Take a look at the code below :
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
      (r'^/$', direct_to_template, { 'template': 'index.html' })
What is this 'direct_to_template' import ? It's django's built-in view, that allows us to load template without specifying any view for it. More to come soon...

May 25, 2010

Tip of the Day #1 - in or not ?

I really love those small python's built in functions and operators. How to check if variable is in some collection ?

>>> z = x in s
>>> z
z will return True if x is in s. Isn't that cool or what ?

Faking URL values

Let's say we have a shop, with product urls looking like this:

But also we have a page for top selling products:

, that uses the same view:
def products_list(request, parent_category, child_category):
How we can avoid writing another view for top sellers, that don't send either parent_ or child_ categories in URL's ?
urlpatterns = patterns('',
    (r'^topsellers/$', views.products_list, {'parent_category': 'topsellers', 'child_category': 'topsellers'}),
    (r'^(?P\w)/(?P\w)/$', views.products_list),

Also I've taken request to create application for simple management of orders, stocks, warranty operations from some hospital-stuff oriented company. So generally in about two months I need to learn how to write market-ready applications in python, with generating pdf's. I'm still not sure if that was a good idea (but you know how it is when pal asks you to do him a favour - especially if he is your former boss :P ).

May 22, 2010

Don't add unnecessary Context Processors

I guess we've all came across problem of using some attributes of our models in the templates. We know the solution for this : create your own context processor, add necessary values there, and voila ! We can use them across our site. But do we really always need to do this ?

Probably the most commonly used object is our User. We often need to check if the user is logged etc. But do we really have to add our user to a new Context Processor like this :
def user(request):
    if hasattr(request, 'user'):
        return {'user':request.user }
    return {}

Let's just take a look at our file. By default (in Django 1.2) TEMPLATE_CONTEXT_PROCESSORS variable looks like this :


And looking into documentation we can find :

"user -- An auth.User instance representing the currently logged-in user (or an AnonymousUser instance, if the client isn't logged in)."

Voila again ! Orly ? Well not exactly. Yes, this gives us ability to check {{ user.username }} and check if a User is authenticated. But what if we have another Model defining our user, with additional fields (and inheriting from contrib User)? Don't panic. There's also solution concerning this fact. Let's say our extended user model is called UserProfile. Open once again and insert this line :

AUTH_PROFILE_MODULE = 'accounts.UserProfile',

where 'accounts' is the name of the app where you're storing your extended model. And now as Django Docs say :

"When a user profile model has been defined and specified in this manner, each User object will have a method -- get_profile() -- which returns the instance of the user profile model associated with that User."

May 20, 2010

Beginning C++

Two solutions for counting average of x < 100 numbers.
int tab100];
    int n=0;
    int number=0;
    char input[10];

    while (n++ < 100)
       cout << "Give " << n << " number : ";
       memset(input, 0x00, 10);
       cin.getline(input, 10);
       number = atoi(input);
       if (number > 0)
           tab[n-1] = number;
    cout << average(tab, n-1) << endl; 
    return 0;

int main()
    const size_t COUNT = 100;
    int tab[COUNT];
    size_t n;   


    for (n = 0; n < COUNT; ++n ) {
        cout << "Give " << n+1 << " number : ";
        cin >> tab[n];

        if (!cin)

    if (n > 0)
        cout << average(tab, n) << endl;
    return 0;

Which one do you prefer ?

May 19, 2010

Python's all() function usage.

Recently I've came across superb python function all(). What it does is just selecting all items,variables,objects,etc fulfilling some requirements. Usage :


Here's my code from Django-LFS (used on website). It's a function deactivating products if they have no stocks (also using my function get_stock_amount, which simply returns stocks of product). Still in development though, gotta add some control from management panel.

def deactivate(self):
        """If there are no stocks, deactivate the product. Used in last step of checkout.

        inactive = False
        if self.is_variant():
            prod = self.parent
            inactive = all(var.get_stock_amount() == 0 for var in prod.variants.filter(active=True))
            if inactive:
       = 0
            if self.get_stock_amount() == 0:
       = 0

[Python] Joining two lists in a dictionary

Hello and welcome everybody.
First entry, so something pythonic for starters. Simple function for joining two lists in a dictionary. If anyone has better idea, leave a comment.

def mapper(keys, values):
n = len(keys)
return [dict(zip(keys, values[i:i + n]))
for i in range(0, len(values), n)]