<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7456076804996318821</id><updated>2012-02-16T12:50:32.041+01:00</updated><category term='generator-expression'/><category term='javascript'/><category term='django-urls'/><category term='lists'/><category term='python-twitter'/><category term='parsing'/><category term='functions'/><category term='youtube'/><category term='settings'/><category term='form'/><category term='string'/><category term='pointers'/><category term='context-processors'/><category term='django-contrib'/><category term='python'/><category term='youtube-api'/><category term='oauth'/><category term='JSON'/><category term='database'/><category term='apache'/><category term='twitter-api'/><category term='generic-views'/><category term='urls'/><category term='jQuery'/><category term='feed'/><category term='variable'/><category term='java'/><category term='dateutil'/><category term='arrays'/><category term='ajax'/><category term='views'/><category term='ajax-pagination'/><category term='object'/><category term='django'/><category term='links'/><category term='filter'/><category term='uniqueness'/><category term='pagination'/><category term='guuid'/><category term='django-template'/><category term='unique slug'/><category term='python lambda'/><category term='twitter'/><category term='dictionary'/><category term='operators'/><category term='collections'/><category term='datetime'/><category term='redundancy'/><category term='cpp'/><category term='django-syncr'/><title type='text'>From zero to code hero</title><subtitle type='html'>Blog about programming and new technologies in general I've created for myself, to memorize briliant solutions of problems, my own parts of code written previously and some general ideas of workarounds. You can find here Python, Java, JavaScript, C++, Django, jQuery.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>29</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-6738713655973706675</id><published>2011-07-18T07:41:00.001+02:00</published><updated>2011-07-18T07:42:06.524+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='ajax'/><category scheme='http://www.blogger.com/atom/ns#' term='ajax-pagination'/><category scheme='http://www.blogger.com/atom/ns#' term='jQuery'/><title type='text'>Django AJAX Tutorial Part 3 - ajax pagination #2</title><content type='html'>Hello. After long time not seen I'm back to finish the topic of pagination in django with AJAX and after few posts also django topic as a whole. The reason is simple - I've switched totally to javascript and ExtJs framework. So let's get started !&lt;br /&gt;&lt;br /&gt;Ok, so we'll be using the same 'Friend' model, so I'll skip the code here. Next go the urls :&lt;br /&gt;&lt;br /&gt;First address is for the main page of our sample project. We won't be using it anywhere in the code. Next is the address of view which generates the friends list. The index view as well as view for changing page will be sending requests there. Finally the last link is for the change page function. For sake of simplicity we'll be using named urls here.&lt;br /&gt;Next - the views, and we'll start from the index view :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;per_page = 4&lt;br /&gt;&lt;br /&gt;def index(request):&lt;br /&gt;    template_name = 'pagination/index2.html'&lt;br /&gt;    html,pagination = load_friends_list(request)&lt;br /&gt;&lt;br /&gt;    return render_to_response(template_name, {"html": html, 'pagination': pagination}, context_instance=RequestContext(request))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The per_page variable remains the same as previously. In the function itself not much to say about. We assign result of calling load_friends_list function to two variables and then include them in the rendered template.&lt;br /&gt;Can we proceed to the next view ? If yes - the friends list generator comes into scene.&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;def load_friends_list(request):&lt;br /&gt;    objects = Friend.objects.all()&lt;br /&gt;    template_name = 'pagination/friends2.html'&lt;br /&gt;    paginator = Paginator(objects, per_page)&lt;br /&gt;    p = request.session.get("pagination_page", request.REQUEST.get("page", 1))&lt;br /&gt;&lt;br /&gt;    pages = paginator.num_pages&lt;br /&gt;    try:&lt;br /&gt;        page = paginator.page(p)&lt;br /&gt;    except EmptyPage:&lt;br /&gt;        page = 0&lt;br /&gt;&lt;br /&gt;    friends = render_to_string(template_name, RequestContext(request, {&lt;br /&gt;        "page" : page,&lt;br /&gt;    }))&lt;br /&gt;    &lt;br /&gt;    pagination = render_to_string('pagination/pagination.html', RequestContext(request, {&lt;br /&gt;        "page" : page,&lt;br /&gt;        "pages": pages        &lt;br /&gt;    }))&lt;br /&gt;&lt;br /&gt;    return (friends, pagination)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now let's go through this code above. First two lines of the function don't need explenations I guess. Then we're creating the Paginator object, calling it's constructor with two arguments - our objects list that we want to paginate and the amount of items per page.&lt;br /&gt;The next line is responsible for getting the current page number. As you'll see in a minute, the change page function can set a session variable for storing the current page value. If that didn't happen we're doing a lookup through REQUEST object ( which is added to each request ) for 'page' variable. And if it's not present - we're picking the first page.&lt;br /&gt;Proceeding further we're storing total number of pages using the built-in Paginator function 'num_pages'(&lt;a href="https://docs.djangoproject.com/en/dev/topics/pagination/?from=olddocs"&gt;here's the link to docs concerning this topic&lt;/a&gt; ). Next we're doing a try-catch check to finally get our paginated objects. By calling the 'page' function of Paginator we're receiving the objects list from the desired page. If this page does not exist we're setting value 0.&lt;br /&gt;Finally we need to render all those things to be used in templates. First goes paginated friends&lt;br /&gt;list object. Next we're rendering pagination sending page object as well and amount of pages (which is not really needed but simplifies the template).&lt;br /&gt;We could have had returned here friends list together with pagination in one template, but I didn't wanted to change the page structure.&lt;br /&gt;&lt;br /&gt;Finally the last view, for setting the current page.&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;def set_friends_page(request):    &lt;br /&gt;    request.session["pagination_page"] = request.GET.get("page", 1)    &lt;br /&gt;    html = load_friends_list(request)[0]&lt;br /&gt;    result = simplejson.dumps({"html" : html}, cls = LazyEncoder)&lt;br /&gt;    return HttpResponse(result)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This view starts with getting the 'page' number from request and storing it in a session variable. If 'page' is not present in the request, we're setting it to the first page. Then we're using previously described function load_friends_list to generate list of paginated objects. As you can see we pick only the first argument from the returned value which is the friends list itself. Finally we can build the result response ( we're using the LazyEncoder described in the first tutorial concerning Ajax) and retunrn it via HttpResponse.&lt;br /&gt;&lt;br /&gt;If we already have that we can get to the last part - the templates. First the templates for friends and pagination, as not much is going on there :&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;{% if page.objects_list %}&lt;br /&gt; &amp;lt;ul class="friends-list"&amp;gt;&lt;br /&gt;  {% for f in page.object_list  %}&lt;br /&gt;   &amp;lt;li&amp;gt;&lt;br /&gt;    &amp;lt;div class="friend-avatar"&amp;gt;&lt;br /&gt;     &amp;lt;img src="http://a2.twimg.com/profile_images/1116899230/mb_normal.png" /&amp;gt;&lt;br /&gt;    &amp;lt;/div&amp;gt;&lt;br /&gt;    &amp;lt;div class="friend-name"&amp;gt;&lt;br /&gt;     &amp;lt;p&amp;gt;{{ f.name }}&amp;lt;/p&amp;gt;&lt;br /&gt;    &amp;lt;/div&amp;gt;&lt;br /&gt;   &amp;lt;/li&amp;gt;&lt;br /&gt;  {% endfor %}&lt;br /&gt; &amp;lt;/ul&amp;gt;&lt;br /&gt;{% else %}&lt;br /&gt; &amp;lt;p&amp;gt;You have no friends.&amp;lt;/p&amp;gt;&lt;br /&gt;{% endif %}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;'friends' template have basically the same structure as in the previous tutorial. We've just changed the source of paginated objects to objects_list parameter of the page objects (which was generated by Paginator as you already know) and moved here the test for friends existence&lt;br /&gt;&lt;br /&gt;Now the pagination template :&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;&amp;lt;ul id="pagination"&amp;gt;&lt;br /&gt;    {% if pages %}&lt;br /&gt;        {% ifequal pages 1 %}&lt;br /&gt;            &amp;lt;li id="{{pages}}"&amp;gt;{{pages}}&amp;lt;/li&amp;gt;&lt;br /&gt;        {% else %}&lt;br /&gt;            {% for i in page.paginator.page_range %}&lt;br /&gt;                &amp;lt;li id="{{i}}"&amp;gt;{{i}}&amp;lt;/li&amp;gt;&lt;br /&gt;            {% endfor %}                        &lt;br /&gt;        {% endifequal %}&lt;br /&gt;    {% endif %}&lt;br /&gt;&amp;lt;/ul&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;First we're checking if pagination will be present at all (if there were no objects to paginate, the amount of pages would be 0 and so there would be no pagination. We could have used page.paginator.num_pages here but it needs much more chars to describe as well as requires a lookup in the page object. So why bother ? :) )&lt;br /&gt;If the amount of pages is one, we just insert one list element. If the amount is greater than one we'll iterate through page.paginator.page_range parameter which has the form of an array (ie. [1,2,3]). And that's all for the pagination. Finally we can get to the index tpl.&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;&amp;lt;div style=\&amp;quot;margin-top:15px; border-top:1px solid #E1E6EC\&amp;quot;&amp;gt;&lt;br /&gt;        &amp;lt;div class=\&amp;quot;friendsList\&amp;quot;&amp;gt;&lt;br /&gt;            &amp;lt;div id=\&amp;quot;loading\&amp;quot;&amp;gt;&lt;br /&gt;            &amp;lt;/div&amp;gt;&lt;br /&gt;            &amp;lt;h2 class=\&amp;quot;div-title\&amp;quot;&amp;gt;&lt;br /&gt;                Friends&lt;br /&gt;            &amp;lt;/h2&amp;gt;&lt;br /&gt;            &amp;lt;div class=\&amp;quot;div-content\&amp;quot;&amp;gt;&lt;br /&gt;                &amp;lt;div id=\&amp;quot;friends-data\&amp;quot;&amp;gt;                     &lt;br /&gt;                    {{ html|safe }}&lt;br /&gt;                &amp;lt;/div&amp;gt;           &lt;br /&gt;            &amp;lt;/div&amp;gt;&lt;br /&gt;            {{ pagination|safe }}&lt;br /&gt;        &amp;lt;/div&amp;gt;&lt;br /&gt;    &amp;lt;/div&amp;gt;   &lt;br /&gt;&amp;lt;script type=\&amp;quot;text/javascript\&amp;quot;&amp;gt;&lt;br /&gt;&amp;lt;/script&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;First of all I've cut the script out as I want to describe it separately. As for the template itself basically nothing to write here about. Sctructure is mainly the same as previously. We have just inserted our two generated variables : the friends list and pagination. We're using 'safe' filter on them so that html tags won't be escaped. The last code belongs to the javascript required for handling ajax requests.&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;$(function(){  &lt;br /&gt; function showLoader(){&lt;br /&gt;     $("#loading").fadeIn(500,0);&lt;br /&gt;  $("#loading").html("&lt;img src='{{ MEDIA_URL }}pagination/loader.gif' /&gt;");&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; function hideLoader(){&lt;br /&gt;  $("#loading").fadeOut('slow');&lt;br /&gt; };&lt;br /&gt; &lt;br /&gt; $("#pagination li:first").addClass('selected');&lt;br /&gt;&lt;br /&gt; $("#pagination li").click(function(){   &lt;br /&gt;  showLoader(); &lt;br /&gt;  $("#pagination li").removeClass();&lt;br /&gt;  $(this).addClass('selected');&lt;br /&gt;  var pageNum = this.id;&lt;br /&gt;&lt;br /&gt;        $.ajax({&lt;br /&gt;            type: "GET",&lt;br /&gt;            url: "{% url set_friends_page %}",&lt;br /&gt;            data: "page="+pageNum,&lt;br /&gt;            async: false,&lt;br /&gt;            dataType: 'json',&lt;br /&gt;            success: function(data){&lt;br /&gt;                el = $('#friends-data');&lt;br /&gt;                $("#friends-data").html(data.html);&lt;br /&gt;                hideLoader();&lt;br /&gt;            }&lt;br /&gt;        });&lt;br /&gt;        return false;        &lt;br /&gt; });&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;As previously we're using jQuery for the sake of simplicity. Also first two functions are exactly the same - they either hide or show the loader div by changing it's display type. Next line sets the class of first pagination element to 'selected'. Finally the most important function - click event handler for pagination&lt;br /&gt;list elements. So each time user clicks &amp;lt;li&amp;gt; element we call this function. First we show the loader, and remove class from all pagination list &amp;lt;li&amp;gt; elements. Next we add class 'selected' to the currently clicked element by using this variable. Before performing ajax request there's just one last thing to do which is storing the id of clicked element to pageNum variable.&lt;br /&gt;Now the fun part - we will do a proper ajax request using jQuery's built in 'ajax' function. In a nutshell it all just comes down to doing a request at our change page view url and then handle the returned data. &lt;br /&gt;Before doing a request we must set some initial parameters which are: the type of request ('GET', 'POST' etc.) url of request (which in this example is our set_friends_page view url), data that we will send (which is the 'page' variable that we're processing later in our views), asynchronousity (if the request blocks the UI or not. Here we do not need the request to be asynchronous as there's not much for the user to do during page load), type of returned data and callback function called when ajax calls ends with success.&lt;br /&gt;The last parameter is the one responsible for performing the html update operation. As a result of our ajax request we're receiving json (of the following form {"html": "&amp;lt;ul&amp;gt;....&amp;lt;/ul&amp;gt;"} ) object containing one parameter : html. This data.html contains the rendered list of friends for proper page number. So we select friends-data div from the DOM and in the next step insert the returned html inside this div with jquery's 'html' function. After that we hide the loader div once again.&lt;br /&gt;&lt;br /&gt;So basically that's all for this episode of 'Ajax with Django' tutorial. Hope you liked it and if something is not clear or if you have some other questions, just leave a comment or find me on twitter. I'm aware of the fact, that this code has some bugs like the fact that stored session variable is not being reseted each time we're refreshing the example page which may lead that we have different than first page loaded but first page selected in the navigation but really I've tried to keep it simple.&lt;br /&gt;I've created a demo so you can check how it works :&lt;br /&gt;&lt;a href="http://samples.fromzerotocodehero.x14.eu/pagination2/start"&gt;http://samples.fromzerotocodehero.x14.eu/pagination2/start&lt;/a&gt;&lt;br /&gt;, as well as prepared the code for download:&lt;br /&gt;&lt;a href="http://ofcjs.x14.eu/pagination2.rar"&gt;http://ofcjs.x14.eu/pagination2.rar&lt;/a&gt;&lt;br /&gt;I will try to put next tutorials in the next few days to finish the series. So stay tooned.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-6738713655973706675?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/6738713655973706675/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/07/django-ajax-tutorial-part-2-ajax.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/6738713655973706675'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/6738713655973706675'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/07/django-ajax-tutorial-part-2-ajax.html' title='Django AJAX Tutorial Part 3 - ajax pagination #2'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-4378790367264753897</id><published>2011-05-09T01:28:00.001+02:00</published><updated>2011-05-09T01:29:02.683+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='links'/><title type='text'>Break</title><content type='html'>Sorry for not updating my blog recently, but it's connected to a switch in  my interests which now concern more javascript than django/python. Still in the next few days I'm gonna finish my pagination with django 'series' as well as post some nice small chat app which I think you will like. So stay tooned, and for now check those links :&lt;br /&gt;&lt;br /&gt;&lt;a href="microjs.com"&gt;microjs.com&lt;/a&gt; - forget about jquery. Use small (up to 5kb) libs containing only what you need.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://mibbu.eu"&gt;mibbu.eu&lt;/a&gt; - cool small gamedev framework from me mate &lt;a href="http://michalbe.blogspot.com"&gt;michalbe&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="https://microsoft.promo.eprize.com/ie9app/gallery"&gt;{dev:unplugged}&lt;/a&gt; - competition from Microsoft for HTML5 games. Some of them look really nice.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-4378790367264753897?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/4378790367264753897/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/05/break.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4378790367264753897'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4378790367264753897'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/05/break.html' title='Break'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-9205479683188013068</id><published>2011-02-03T22:24:00.003+01:00</published><updated>2011-02-03T22:47:44.021+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='ajax'/><category scheme='http://www.blogger.com/atom/ns#' term='ajax-pagination'/><category scheme='http://www.blogger.com/atom/ns#' term='pagination'/><category scheme='http://www.blogger.com/atom/ns#' term='jQuery'/><title type='text'>Django AJAX Tutorial Part 2 - ajax pagination #1</title><content type='html'>Hello again. For some time now I will continue my tutorials concerning using AJAX with Django. I have received few requests to write about pagination next, so this is the topic for today's post. In the last months I went through few different methods of ajax pagination. I will try to show you at least three but each in different post.&lt;br /&gt;The one I'm going to write about today was the first I've tried. It uses built-in django generic views. &lt;br /&gt;&lt;br /&gt;Let's begin with views, as they're most important here :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;#!/usr/bin/env python&lt;br /&gt;# encoding: utf-8&lt;br /&gt;#Python&lt;br /&gt;import math&lt;br /&gt;&lt;br /&gt;#Django&lt;br /&gt;from django.conf import settings&lt;br /&gt;from django.shortcuts import render_to_response&lt;br /&gt;from django.template import RequestContext&lt;br /&gt;from django.views.generic.list_detail import object_list&lt;br /&gt;&lt;br /&gt;#Project&lt;br /&gt;from models import Friend&lt;br /&gt;&lt;br /&gt;#we're importing LazyEncoder written in first part of Django - Ajax tutorial&lt;br /&gt;from tutorial_utils import LazyEncoder&lt;br /&gt;&lt;br /&gt;# 'global' variable storing amount of objects per page&lt;br /&gt;per_page = 4&lt;br /&gt;&lt;br /&gt;def index(request):&lt;br /&gt;    &lt;br /&gt;    #we take all object's that we want to be paginated&lt;br /&gt;    friends = Friend.objects.all()&lt;br /&gt;    &lt;br /&gt;    #count them&lt;br /&gt;    count = friends.count()&lt;br /&gt;    &lt;br /&gt;    #count amount of pages&lt;br /&gt;    pages = math.ceil(count / float(per_page))&lt;br /&gt;    pages = int(pages)&lt;br /&gt;    &lt;br /&gt;    #create list of pages&lt;br /&gt;    pages = range(1, pages+1)&lt;br /&gt;&lt;br /&gt;    #if amount of objects is smaller than per_page variable, we create only one page&lt;br /&gt;    if count &lt;= per_page:&lt;br /&gt;        pages = 1&lt;br /&gt;&lt;br /&gt;    return render_to_response('pagination/index1.html', {&lt;br /&gt;            'pages': pages, 'count': count&lt;br /&gt;            }, context_instance=RequestContext(request))&lt;br /&gt;&lt;br /&gt;#this view will create us list of friends&lt;br /&gt;def friends_list(request):&lt;br /&gt;&lt;br /&gt;    #first take all objects       &lt;br /&gt;    friends = Friend.objects.all()   &lt;br /&gt;    template = 'pagination/friends1.html'&lt;br /&gt;    &lt;br /&gt;    #using generic view display list of objects paginated by 'pagenate_by' elements. Good part about using object_ilst generic view is that it automatically paginates elements and then allows showing the desired page by accessing 'page_with_objects_url' + ?page=number_of_page. we will take advantage of this in our example.&lt;br /&gt;&lt;br /&gt;    return object_list(request, &lt;br /&gt;        queryset = friends,&lt;br /&gt;        paginate_by = per_page,&lt;br /&gt;        template_name = template,&lt;br /&gt;        extra_context = {}&lt;br /&gt;        )&lt;br /&gt;&lt;/pre&gt;Ok so idea is that we use generic view 'object_list' that paginates objects for us and creates links for each page. So now let's take a look at urls :&lt;pre class="python" name="code"&gt;from django.conf.urls.defaults import *&lt;br /&gt;from views import *&lt;br /&gt;&lt;br /&gt;urlpatterns = patterns('',&lt;br /&gt;    url(r'^start$', index, name="index"),&lt;br /&gt;    url(r'^friends_list/$', friends_list),&lt;br /&gt;)&lt;br /&gt;&lt;/pre&gt;Nothing complicated here. I'm not using named urls here to make it easier to understand in the javascript part. Next thing are the templates. First I'll present the one responsible for creating list of friends (props go to &lt;a href="http://michalbe.blogspot.com"&gt;michalbe&lt;/a&gt; for lending me his twitter avatar :)) :&lt;pre class="js" name="code"&gt;&lt;ul class="friends-list"&gt;{% for f in object_list %}&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="friend-avatar"&gt;&lt;img src="http://a2.twimg.com/profile_images/1116899230/mb_normal.png" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="friend-name"&gt;&lt;p&gt;{{ f.name }}&lt;/p&gt;&lt;/div&gt;&lt;/li&gt;&lt;br /&gt;{% endfor %}     &lt;/ul&gt;&lt;/pre&gt;And main template with the pagination part :&lt;pre class="js" name="code"&gt;&lt;div style="margin-top:15px; border-top:1px solid #E1E6EC"&gt;&lt;div class="friendsList"&gt;&lt;div id="loading"&gt;&lt;/div&gt;&lt;h2 class="div-title"&gt;Friends&lt;/h2&gt;&lt;div class="div-content"&gt;&lt;div class="friends-data"&gt;&lt;/div&gt;&lt;/div&gt;{% ifequal count 0 %}&lt;br /&gt;                  &lt;p&gt;You have no friends.&lt;/p&gt;{% else %}&lt;br /&gt;                 &lt;ul id="pagination"&gt;{% if pages %}                                                   {% ifequal pages 1 %}&lt;br /&gt;&lt;li id="{{pages}}"&gt;{{pages}}&lt;/li&gt;&lt;br /&gt;{% else %}                                                           {% for i in pages %}&lt;br /&gt;&lt;li id="{{i}}"&gt;{{i}}&lt;/li&gt;&lt;br /&gt;{% endfor %}{% endifequal %}{% endif %}                  &lt;/ul&gt;{% endifequal %}&lt;br /&gt;        &lt;/div&gt;&lt;/div&gt;&lt;/pre&gt;As you can see here I've included pagination in this template (so that it won't be refreshed each time user changes page). If number of pages is none, we're showing appropriate alert. Else if there is only one page, we're not using loop because we would get two pages in fact (page 0 and 1). If there are more pages, we're just going through a for loop adding each of them and setting their id's to page number. we will need that in the js part which comes next. Once again I'm using jQuery here to keep it simple and take advantage of it's built in function &lt;a href="http://api.jquery.com/load/"&gt;'load'&lt;/a&gt; that reads content under specified address and then includes it html of our page :&lt;pre class="js" name="code"&gt;&lt;script type="text/javascript"&gt;&lt;br /&gt;$(function(){  &lt;br /&gt;&lt;br /&gt;        //function displaying traditional 'ajax loader' with some smooth effect&lt;br /&gt; function showLoader(){&lt;br /&gt;     $("#loading").fadeIn(500,0);&lt;br /&gt;  $("#loading").html("&lt;img src='{{ MEDIA_URL }}pagination/loader.gif' /&gt;");&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;        //function for hiding loader&lt;br /&gt; function hideLoader(){&lt;br /&gt;  $("#loading").fadeOut('slow');&lt;br /&gt; };&lt;br /&gt; &lt;br /&gt;        //we're setting style for first page link which is selected by default&lt;br /&gt; $("#pagination li:first").addClass('selected');&lt;br /&gt;&lt;br /&gt;        //now we load content generated for the first page by our generic view under friends_list address&lt;br /&gt;&lt;br /&gt; $(".friends-data").load("/pagination1/friends_list/?page=1");&lt;br /&gt;&lt;br /&gt;        //now tiny bit of jquery magic - when user clicks page number we will grab id of the clicked li (which as you remember is the same as page number) and load content for this page in the same way we did this 2 lines above&lt;br /&gt;&lt;br /&gt; $("#pagination li").click(function(){&lt;br /&gt;                //before loading show loader graphics   &lt;br /&gt;  showLoader(); &lt;br /&gt;  $("#pagination li").removeClass();&lt;br /&gt;  $(this).addClass('selected');&lt;br /&gt;  var pageNum = this.id; &lt;br /&gt;  $(".friends-data").load("/pagination1/friends_list/?page=" + pageNum, hideLoader());&lt;br /&gt;                //after loading hide loader&lt;br /&gt; });&lt;br /&gt;});&lt;br /&gt;&lt;/script&gt;&lt;br /&gt;&lt;/pre&gt;Ok, so that's the whole code for today. As previously I've created working example for you under this link :&lt;a href="http://samples.fromzerotocodehero.x14.eu/pagination1/start"&gt;http://samples.fromzerotocodehero.x14.eu/pagination1/start&lt;/a&gt;And here's a downloadable package (soon I'll move all of this to my git account I promise :) ):&lt;a href="http://ofcjs.x14.eu/pagination1.zip"&gt;http://ofcjs.x14.eu/pagination1.zip&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-9205479683188013068?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/9205479683188013068/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/02/django-ajax-tutorial-part-2-ajax.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/9205479683188013068'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/9205479683188013068'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/02/django-ajax-tutorial-part-2-ajax.html' title='Django AJAX Tutorial Part 2 - ajax pagination #1'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-5372126501652984757</id><published>2011-01-31T18:32:00.003+01:00</published><updated>2011-01-31T19:19:36.342+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='JSON'/><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='form'/><category scheme='http://www.blogger.com/atom/ns#' term='ajax'/><category scheme='http://www.blogger.com/atom/ns#' term='jQuery'/><title type='text'>Django AJAX Tutorial Part 1 - adding email to newsletter</title><content type='html'>This is something I really wanted to write about since some time - using ajax with django. The cause is simple - internet is lacking good materials concerning this matter. And I remember having many problems with ajax in the beginning. That's why in the next few days I will show typical usage of ajax with django, like form validation, pagination and simple shoutbox. &lt;br /&gt;&lt;br /&gt;Ok - the basics. First thing you need to understand - when talking about ajax here  we mean a request which is sent from the browser by javascript, usually asynchronously ( meaning user can do other things while we're processing it). So to keep it simple - ajax is the 'request' we're using in our django views. And instead of reloading the whole page after user clicks some link or submits form we can first process it in the background and then refresh only the needed parts of the page. Sounds pretty facebookish doesn't it ? :) And there's no magic in it, really.&lt;br /&gt;&lt;br /&gt;Let's start from the simplest possible example - we will allow user to add email to some newsletter. Here is tho code for model, url and form :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;class NewsletterForm(forms.Form):&lt;br /&gt;    email = forms.EmailField(label=_("E-mail address"))&lt;br /&gt;&lt;br /&gt;class NewsletterEmails(models.Model):&lt;br /&gt;    email = models.EmailField(_(u"E-mail address"),)&lt;br /&gt;&lt;br /&gt;urlpatterns = patterns('',&lt;br /&gt;    url(r'^newsletter_add/$', newsletter_add, name="newsletter_add"),&lt;br /&gt;)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Nothing unexpected here I guess. Simple model, simple form with just one field and a link to our view (remember - even though we're not redirecting user to this link, we still need a way to call our view function processing the email).&lt;br /&gt;Next comes the view function :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django.http import HttpResponse&lt;br /&gt;from django.template.loader import render_to_string&lt;br /&gt;from django.utils import simplejson&lt;br /&gt;from django.utils.functional import Promise&lt;br /&gt;from django.utils.encoding import force_unicode&lt;br /&gt;from models import NewsletterEmails&lt;br /&gt;from forms import NewsletterForm&lt;br /&gt;&lt;br /&gt;#here is some magic. We need to write custom JSON encoder, since sometimes&lt;br /&gt;#serializing lazy strings can cause errors. &lt;br /&gt;#You need to write it only once and then can reuse in any app&lt;br /&gt;&lt;br /&gt;class LazyEncoder(simplejson.JSONEncoder):&lt;br /&gt;    """Encodes django's lazy i18n strings.&lt;br /&gt;    """&lt;br /&gt;    def default(self, obj):&lt;br /&gt;        if isinstance(obj, Promise):&lt;br /&gt;            return force_unicode(obj)&lt;br /&gt;        return obj&lt;br /&gt;&lt;br /&gt;#here the view function starts&lt;br /&gt;def newsletter_add(request):&lt;br /&gt;&lt;br /&gt;    #as usual when processing forms we check if the method was POST/GET&lt;br /&gt;    if request.method == "POST":&lt;br /&gt;&lt;br /&gt;        #we get email address from request variables      &lt;br /&gt;        adr = request.POST['email']&lt;br /&gt;        e = None&lt;br /&gt;&lt;br /&gt;        #we process address only if it's longer than 6 characters.&lt;br /&gt;        #this assures us than we won't waste server time on&lt;br /&gt;        #addresses like 'oeui' or 'u@u.u' &lt;br /&gt;        if len(adr) &gt; 6:&lt;br /&gt;            &lt;br /&gt;            #create form instance and fill it with data. In this case it will only be the email address&lt;br /&gt;            form = NewsletterForm(data=request.POST)&lt;br /&gt;            &lt;br /&gt;            #let django perform the validation&lt;br /&gt;            if form.is_valid():&lt;br /&gt;&lt;br /&gt;                #check if the email address is not already in our database&lt;br /&gt;                try:&lt;br /&gt;                    e = NewsletterEmails.objects.get(email = adr)&lt;br /&gt;                    message = _(u"Email already added.")&lt;br /&gt;                    type = "error"&lt;br /&gt;                except NewsletterEmails.DoesNotExist:&lt;br /&gt;&lt;br /&gt;                    if DoesNotExist exception was caught we add the address 'safe-mode' using try/catch&lt;br /&gt;                    try:&lt;br /&gt;                        e = NewsletterEmails(email = adr)&lt;br /&gt;                    except DoesNotExist:&lt;br /&gt;                        pass&lt;br /&gt;                    message = _(u"Email added.")&lt;br /&gt;                    type = "success"&lt;br /&gt;                    e.save()&lt;br /&gt;            else:&lt;br /&gt;                message = _(u"Bad address.")&lt;br /&gt;                type = "error"                &lt;br /&gt;        else:&lt;br /&gt;            message = _(u"Too short address.")&lt;br /&gt;            type = "error"&lt;br /&gt;&lt;br /&gt;    #we don't need to do this but it's good practice to check the source of request. If it comes from ajax call we build the response.&lt;br /&gt;&lt;br /&gt;    if request.is_ajax():&lt;br /&gt;        #let built in simplejson package serialize our data. It means we transform everything to simple strings.&lt;br /&gt;        result = simplejson.dumps({&lt;br /&gt;            "message": message,&lt;br /&gt;            "type": type,&lt;br /&gt;        }, cls=LazyEncoder)&lt;br /&gt;&lt;br /&gt;        #return the response&lt;br /&gt;        return HttpResponse(result, mimetype='application/javascript')&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now the form. This is really basic so I won't say anything more about it apart of the fact that we explicitly set the action of our form to address of view processing addition of emails :&lt;br /&gt;&lt;br /&gt;&lt;pre class="js" name="code"&gt;&lt;form action="{% url newsletter_add %}" method="post" class="form-newsletter" id="form-newsletter"&gt;&lt;input name="email" type="text" class="form-text" /&gt;&lt;br /&gt;            &lt;input type="submit" value="Add" class="form-submit" /&gt;&lt;br /&gt;        &lt;/form&gt;&lt;/pre&gt;&lt;br /&gt;and finally the javascript part. I'm using &lt;a href="http://jquery.com/"&gt;jQuery javascript library&lt;/a&gt; here as well as &lt;a href="http://jquery.malsup.com/form/"&gt;jQuery's form plugin&lt;/a&gt; for processing forms. It simply adds method that takes all the values from form's fields and sends it to specified address (in this case it'll be "newsletter_add"). We could do this by ourselves, but that's not what this tutorial is about.&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;&lt;script&gt;&lt;br /&gt;    &lt;br /&gt;    //function that will disable form's button so that user cannot send multiple requests to our function. It takes boolean value and id of the form.&lt;br /&gt;&lt;br /&gt;    var disableSubmit = function(val, id){&lt;br /&gt;        $(id + ' input[type=submit]').attr('disabled', val);&lt;br /&gt;    };   &lt;br /&gt;    &lt;br /&gt;    //the fun starts here. On click of 'form-submit' button we run a function&lt;br /&gt;&lt;br /&gt;    $('.form-submit').click(function() {&lt;br /&gt;&lt;br /&gt;        //we are storing form object, form id, form's action and form message div id in variables&lt;br /&gt;&lt;br /&gt;        var form = $(this).parents("form:first");&lt;br /&gt;        var id = '#' + form.attr('id');&lt;br /&gt;        var action = form.attr('action');&lt;br /&gt;        var form_message = id + '-message';&lt;br /&gt;        &lt;br /&gt;        //now we're disabling submitting buttons&lt;br /&gt;        disableSubmit(true, id);&lt;br /&gt;&lt;br /&gt;//in form's message div add 'Adding...' text as well as change it's class &lt;br /&gt;        $(form_message).removeClass().addClass('loading').html('Adding...').fadeIn();        &lt;br /&gt;        //submit form&lt;br /&gt;&lt;br /&gt;        $(this).parents("form:first").ajaxSubmit({&lt;br /&gt;            dataType: "json",&lt;br /&gt;            "success": function(data) {&lt;br /&gt;                //on successfull submission run this code. First hide message&lt;br /&gt;&lt;br /&gt;                $(form_message).hide();&lt;br /&gt;&lt;br /&gt;//change class of message div to 'type' returned by our view and insert 'message' also returned by json serializer&lt;br /&gt;                $(form_message).removeClass().addClass(data['type']).html(data['message']).fadeIn('slow');&lt;br /&gt;                //allow submitting of form's buttons&lt;br /&gt;&lt;br /&gt;                disableSubmit(false, id);&lt;br /&gt;&lt;br /&gt;                //if email was successfully added&lt;br /&gt;                if(data['type'] == 'success'){&lt;br /&gt;                    &lt;br /&gt;                    //clear all the form's inputs that are not of submission, button, hidden or reset type&lt;br /&gt;&lt;br /&gt;                    $(':input', id).not(':button, :submit, :reset, :hidden').val('');&lt;br /&gt;                }               &lt;br /&gt;            }&lt;br /&gt;        });&lt;br /&gt;        return false;&lt;br /&gt;    });    &lt;br /&gt;&lt;/script&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And basically that will be all for this part. As you can see the key to using AJAX with django is that our views must return serialized strings with JSON so that we can process them with javascript.&lt;br /&gt;&lt;br /&gt;For the first time I have prepared a working example under this link :&lt;br /&gt;&lt;a href=" http://samples.fromzerotocodehero.x14.eu/newsletter1/start"&gt;&lt;br /&gt;http://samples.fromzerotocodehero.x14.eu/newsletter1/start&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;as well as downloadable code :&lt;br /&gt;&lt;br /&gt;&lt;a href="http://ofcjs.x14.eu/ajax1.zip"&gt;http://ofcjs.x14.eu/ajax1.zip&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;If you have any questions feel free to ask in comments or on my &lt;a href="http://twitter.com/sasklacz"&gt;twitter&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-5372126501652984757?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/5372126501652984757/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/01/django-ajax-tutorial-part-1.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/5372126501652984757'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/5372126501652984757'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/01/django-ajax-tutorial-part-1.html' title='Django AJAX Tutorial Part 1 - adding email to newsletter'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-2320300952861033456</id><published>2011-01-28T21:04:00.001+01:00</published><updated>2011-01-28T21:06:13.712+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='parsing'/><category scheme='http://www.blogger.com/atom/ns#' term='youtube-api'/><category scheme='http://www.blogger.com/atom/ns#' term='feed'/><category scheme='http://www.blogger.com/atom/ns#' term='youtube'/><category scheme='http://www.blogger.com/atom/ns#' term='django-syncr'/><title type='text'>Synchronizing youtube user's videos filtered by tags</title><content type='html'>Today I will write about synchronizing your app with youtube and then filtering movies of specific user by tags. But let's get back to the beginning. I assume you already have &lt;a href="http://code.google.com/p/django-sync/"&gt;django-syncr&lt;/a&gt; installed. I also assume that you're using video as attribute of some other object. Basic usage is pretty straightforward, so I'll proceed to some examples.&lt;br /&gt;&lt;br /&gt;First the easiest one - we provide id of video as a string and as a result we receive Video instance :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django-syncr.youtube import YoutubeSyncr&lt;br /&gt;&lt;br /&gt;def sync_video_id(id):&lt;br /&gt;    """ Synchronize single video by given YoutubeID    &lt;br /&gt;    Takes youtube id as a string. Returns Video instance.   &lt;br /&gt;    """&lt;br /&gt;    &lt;br /&gt;    y = YoutubeSyncr()&lt;br /&gt;    try:&lt;br /&gt;        video = y.syncVideo(id)&lt;br /&gt;        return video&lt;br /&gt;    except:    &lt;br /&gt;        return video&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That was easy. Let's try something more complicated then. Next there's a synchronization when provided url to video. Using python's built in urlparse module we divide url into components. Because my actual code needed to be compatible with version 2.4 of python, I'm using cgi module here (the same functions just stored in different place). Here's how this looks step by step. Everything is rather self-explanatory so I will not go through it line by line :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;&gt;&gt;&gt; url = 'http://www.youtube.com/watch?v=mPXxI1uyVEE&amp;feature=rec-LGOUT-exp_fres&lt;br /&gt;h+div-1r-3-HM'&lt;br /&gt;&gt;&gt;&gt; url&lt;br /&gt;'http://www.youtube.com/watch?v=mPXxI1uyVEE&amp;feature=rec-LGOUT-exp_fresh+div-1r-3&lt;br /&gt;-HM'&lt;br /&gt;&gt;&gt;&gt; import urlparse&lt;br /&gt;&gt;&gt;&gt; url_data = urlparse.urlparse(url)&lt;br /&gt;&gt;&gt;&gt; url_data&lt;br /&gt;ParseResult(scheme='http', netloc='www.youtube.com', path='/watch', params='', q&lt;br /&gt;uery='v=mPXxI1uyVEE&amp;feature=rec-LGOUT-exp_fresh+div-1r-3-HM', fragment='')&lt;br /&gt;&gt;&gt;&gt; query = urlparse.parse_qs(url_data[4])&lt;br /&gt;&gt;&gt;&gt; query&lt;br /&gt;{'feature': ['rec-LGOUT-exp_fresh div-1r-3-HM'], 'v': ['mPXxI1uyVEE']}&lt;br /&gt;&gt;&gt;&gt; id = query["v"][0]&lt;br /&gt;&gt;&gt;&gt; id&lt;br /&gt;'mPXxI1uyVEE'&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;and that's how we will do this in django :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django-syncr.youtube import YoutubeSyncr&lt;br /&gt;&lt;br /&gt;def sync_video_url(url):&lt;br /&gt;    """ synchronize single video by it's url    &lt;br /&gt;    Takes video url as a string, returns Video object.&lt;br /&gt;&lt;br /&gt;    """&lt;br /&gt;    import urlparse&lt;br /&gt;    url_data = urlparse.urlparse(url)&lt;br /&gt;    try:&lt;br /&gt;        query = cgi.parse_qs(url_data[4])&lt;br /&gt;    except:&lt;br /&gt;        query = urlparse.parse_qs(url_data[4])&lt;br /&gt;    id = query["v"][0]&lt;br /&gt;    &lt;br /&gt;    y = YoutubeSyncr()&lt;br /&gt;    try:&lt;br /&gt;        return video = y.syncVideo(id)&lt;br /&gt;    except:    &lt;br /&gt;        return none&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;When you're finished warm up It's time for more complex functionality. Now we will sync videos of specific users meeting specified tags requirements. First the core function that will do the work here. Because I tried to make it reusable django's ContentType module is used. :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django.contrib.contenttypes import generic&lt;br /&gt;from django.contrib.contenttypes.models import ContentType&lt;br /&gt;from django-syncr.youtube import YoutubeSyncr&lt;br /&gt;&lt;br /&gt;def sync_video_user(parent,model_name,user,tags):&lt;br /&gt;    """ Sync all videos of user matching given tags pattern .&lt;br /&gt;    &lt;br /&gt;    Takes parent object, object to sync videos (as a string), string with username and string with tags.&lt;br /&gt;    Returns list of synchronized videos. Takes care of already existing videos as well as prevents duplication of slugs.&lt;br /&gt;    """&lt;br /&gt;    &lt;br /&gt;    from django.template.defaultfilters import slugify&lt;br /&gt;    &lt;br /&gt;    #first we need to get the actual model for object holding video.&lt;br /&gt;    model_class = ContentType.objects.get(model=model_name).model_class()&lt;br /&gt;    &lt;br /&gt;    #we create a queryset for searching for duplicates of video we're currently worknig on&lt;br /&gt;    queryset = model_class._default_manager.all()&lt;br /&gt;    &lt;br /&gt;    #parse string of tags to get proper validating url string&lt;br /&gt;    fmt_tags = parse_tags(tags)&lt;br /&gt;&lt;br /&gt;    #request for youtube feed&lt;br /&gt;    feed = get_youtube_feed_url(user, fmt_tags)&lt;br /&gt;    &lt;br /&gt;    #search for videos parsing returned feed&lt;br /&gt;    sync = search_youtube(feed)&lt;br /&gt;&lt;br /&gt;    #create a temporary instance (notice not using save() anywhere here) to get object methods available as well as queryset&lt;br /&gt;    instance = model_class()&lt;br /&gt;&lt;br /&gt;    for vid in sync:&lt;br /&gt;        &lt;br /&gt;        #if our queryset does not already contain object with this video id&lt;br /&gt;        if not queryset.filter(**{"yt_video_id": vid.video_id}):&lt;br /&gt;&lt;br /&gt;            #check if slug is free&lt;br /&gt;            free = try_slug(instance, slugify(vid.title))&lt;br /&gt;            if not free:&lt;br /&gt;                &lt;br /&gt;                #if not use function which we had already discussed some time ago - unqiue_slugify&lt;br /&gt;                free = unique_slugify(instance, slugify(vid.title))&lt;br /&gt;            else:&lt;br /&gt;                free = slugify(vid.title)&lt;br /&gt;&lt;br /&gt;            #create new object&lt;br /&gt;            new = model_class(parent=parent,&lt;br /&gt;                               slug=free,&lt;br /&gt;                               name = vid.title,&lt;br /&gt;                               yt_video_id=vid.video_id,&lt;br /&gt;                               video=vid,&lt;br /&gt;                               publication_date=vid.published, active=True,&lt;br /&gt;                              )&lt;br /&gt;            new.save()&lt;br /&gt;&lt;br /&gt;    return 1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now that we have the main part of the code, we can look on the smaller pieces :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;def parse_tags(tags):&lt;br /&gt;    """&lt;br /&gt;    Parse received string of tags to tags list. Then append them to yt search API address.&lt;br /&gt;    Return path to search api.    &lt;br /&gt;    &lt;br /&gt;    parse_tags(tags):&lt;br /&gt;        url(string)        &lt;br /&gt;    """&lt;br /&gt;&lt;br /&gt;    tags_list = tags.split(',')&lt;br /&gt;    tags_list = [tag.strip() for tag in tags_list]&lt;br /&gt;    tags_list = [re.sub(r"\s+", "+", tag) for tag in tags_list&lt;br /&gt;    parse_string = '&amp;category=%s&amp;v=2' % '%2C+'.join(tag.strip() for tag in tags_list)&lt;br /&gt;&lt;br /&gt;    return parse_string&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Not much magic going on here. We split string of tags and use simple regex to get single tags from it (tags are either separated by commas or more than two whitespaces. Multi-words tags allowed). We then put all tags to query url in the proper form.&lt;br /&gt;&lt;br /&gt;Next function adds our tags to the rest of the query string containing youtube username :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;def get_youtube_feed_url(user, url):&lt;br /&gt;    """ Add username to youtube feed address.&lt;br /&gt;    """&lt;br /&gt;    &lt;br /&gt;    feed = '/feeds/api/videos?author=%s&amp;alt=rss' % user&lt;br /&gt;    feed += url&lt;br /&gt;    return feed&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Finally when we have the whole query url we can perform the search using youtube api :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;def search_youtube(path):&lt;br /&gt;    """ Search videos on youtube&lt;br /&gt;    &lt;br /&gt;    If path is given, connects to youtube feed returns any videos matching query.&lt;br /&gt;    All videos are then synched.&lt;br /&gt;    &lt;br /&gt;    """&lt;br /&gt;    &lt;br /&gt;    if path:&lt;br /&gt;        import feedparser&lt;br /&gt;        import urlparse&lt;br /&gt;        &lt;br /&gt;        YTSearchFeed = feedparser.parse("http://gdata.youtube.com" + path)&lt;br /&gt;        videos = []&lt;br /&gt;        for yt in YTSearchFeed.entries:&lt;br /&gt;&lt;br /&gt;            #the only new part is here. Because returned feed is a really complex json file, we search for 'link' keys that store url to our desired videos       &lt;br /&gt;            url_data = urlparse.urlparse(yt['link'])&lt;br /&gt;            try:&lt;br /&gt;                query = cgi.parse_qs(url_data[4])&lt;br /&gt;            except:&lt;br /&gt;                query = urlparse.parse_qs(url_data[4])&lt;br /&gt;            id = query["v"][0]&lt;br /&gt;            videos.append(id)&lt;br /&gt;        &lt;br /&gt;        synched = []&lt;br /&gt;        for video in videos:&lt;br /&gt;            try:&lt;br /&gt;                sync = sync_video_id(video)&lt;br /&gt;                synched.append(sync)&lt;br /&gt;            except:&lt;br /&gt;                pass&lt;br /&gt;        return synched&lt;br /&gt;    else:&lt;br /&gt;        return []&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And basically we're finished.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-2320300952861033456?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/2320300952861033456/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/01/synchronizing-youtube-users-videos.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/2320300952861033456'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/2320300952861033456'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/01/synchronizing-youtube-users-videos.html' title='Synchronizing youtube user&apos;s videos filtered by tags'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-3936176330048860635</id><published>2011-01-09T23:53:00.002+01:00</published><updated>2011-01-22T22:43:08.431+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='django-urls'/><category scheme='http://www.blogger.com/atom/ns#' term='apache'/><title type='text'>Using ProxyPass with django project</title><content type='html'>Once again I need to postpone my post about django-syncr and youtube since I came across interesting &lt;a href="http://stackoverflow.com/questions/4627013/django-apache-address-problem"&gt;problem&lt;/a&gt; recently. Here's the deal : user has his django app running on some server under some link. Application itself is visible under different link. So apache conf got 'ProxyPass' and 'ProxyPassReverse' added. All seemed to work fine apart of links created with '{% url %}' templatetag (and from what I was able to test also get_absolute_urls could cause problems depending on the method used to create them). Url tag was adding original django application name to the link. Because I'm no good in setting apache I've came up with different solution. After skimming through django/template/defaulttags and django/core/urlesolvers I've realized that rewriting both 'reverse' function and 'url' tag would be tedious and probably unnecessary. Instead I've just added this 'try' block that replaces first unwanted occurence of our app name (which is defined in settings under PROJECT_NAME variable) with empty sign to 'url' templatetag and saved it as custom tag named 'urlc'. Not sure if overriding default tags works, gotta check it some day.&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;else:&lt;br /&gt;                if self.asvar is None:&lt;br /&gt;                    raise e&lt;br /&gt;        &lt;br /&gt;        #code starts here&lt;br /&gt;        try:&lt;br /&gt;            url = url.replace(settings.PROJECT_NAME+'/', '', 1)&lt;br /&gt;        except:&lt;br /&gt;            pass&lt;br /&gt;        #code ends here    &lt;br /&gt;&lt;br /&gt;        if self.asvar:&lt;br /&gt;            context[self.asvar] = url&lt;br /&gt;            return ''&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Not sure if it works for OP, but worked at my test config without bigger problems.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-3936176330048860635?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/3936176330048860635/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/01/using-proxypass-with-django-project.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/3936176330048860635'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/3936176330048860635'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/01/using-proxypass-with-django-project.html' title='Using ProxyPass with django project'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-7870563899189156149</id><published>2011-01-08T01:55:00.000+01:00</published><updated>2011-01-08T01:55:59.710+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='unique slug'/><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='uniqueness'/><title type='text'>Provide unique slugs for model class</title><content type='html'>Sorry my dear readers for this long break between posts, but I have had lots of work lately finishing previous jobs. Recently I've shown you how to synchronize your app with Twitter and also parse list of tweets changing hash tags to proper links. Today I wanted to show you how to synchronize application with youtube but for this purpose I need a way to provide unique slugs for models. So here's the whole code which I'll comment below :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;import re&lt;br /&gt;&lt;br /&gt;from django.template.defaultfilters import slugify&lt;br /&gt;&lt;br /&gt;def try_slug(instance, slug):&lt;br /&gt;    """Check if the slug is free for corresponding model instance&lt;br /&gt;    """&lt;br /&gt;    queryset = instance.__class__._default_manager.all()&lt;br /&gt;    if not queryset.filter(**{"slug": slug}):&lt;br /&gt;        return True&lt;br /&gt;    else:&lt;br /&gt;        return False&lt;br /&gt;&lt;br /&gt;def unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'):&lt;br /&gt;    """Create unique slug&lt;br /&gt;    &lt;br /&gt;    Creates unique slug across model class.&lt;br /&gt;    &lt;br /&gt;    """&lt;br /&gt;    slug_field = instance._meta.get_field(slug_field_name)&lt;br /&gt;    slug_len = slug_field.max_length&lt;br /&gt;&lt;br /&gt;    slug = slugify(value)&lt;br /&gt;    slug = slug[:slug_len]&lt;br /&gt;    slug = _slug_strip(slug, slug_separator)&lt;br /&gt;    original_slug = slug&lt;br /&gt;    &lt;br /&gt;    if queryset is None:&lt;br /&gt;        queryset = instance.__class__._default_manager.all()&lt;br /&gt;    if instance.pk:&lt;br /&gt;        queryset = queryset.exclude(pk=instance.pk)&lt;br /&gt; &lt;br /&gt;    next = 2&lt;br /&gt;    while not slug or queryset.filter(**{slug_field_name: slug}):&lt;br /&gt;        slug = original_slug&lt;br /&gt;        end = '%s%s' % (slug_separator, next)&lt;br /&gt;        if slug_len and len(slug) + len(end) &gt; slug_len:&lt;br /&gt;            slug = slug[:slug_len-len(end)]&lt;br /&gt;            slug = _slug_strip(slug, slug_separator)&lt;br /&gt;        slug = '%s%s' % (slug, end)&lt;br /&gt;        next += 1&lt;br /&gt;    return slug&lt;br /&gt;&lt;br /&gt;def _slug_strip(value, separator='-'):&lt;br /&gt;    """&lt;br /&gt;    Cleans up a slug by removing slug separator characters that occur at the&lt;br /&gt;    beginning or end of a slug.&lt;br /&gt;    """&lt;br /&gt;    separator = separator or ''&lt;br /&gt;    if separator == '-' or not separator:&lt;br /&gt;        re_sep = '-'&lt;br /&gt;    else:&lt;br /&gt;        re_sep = '(?:-|%s)' % re.escape(separator)&lt;br /&gt;&lt;br /&gt;    if separator != re_sep:&lt;br /&gt;        value = re.sub('%s+' % re_sep, separator, value)&lt;br /&gt;&lt;br /&gt;    if separator:&lt;br /&gt;        if separator != '-':&lt;br /&gt;            re_sep = re.escape(separator)&lt;br /&gt;        value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)&lt;br /&gt;    return value&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;So now some explanations to the code. First function gives us possibility to check if slug is free for specific model class. It takes object instance and slug and returns boolean value. Inside the code we take default 'all' manager of the model and filter queryset with slug.&lt;br /&gt;Second function is the key to solving our problem. The unique_slugify function takes shown parameters. At first we check the max length of the slug field, so that we won't exceed its value. Then we slugify our slug with built in django function, cut it if needed and strip of sepparators different than '-' or 'separator' parameter received by function. Next step is to get the queryset on which we will be working, excluding our model instance. Finally the fun begins. In our while loop condition we check existence of newly created slug or result of filtering our queryset. If both are none we take the separator and add next integer to it.&lt;br /&gt;If the length of concatenated slug and identifier is too long, we cut it off. Finally we're creating slug that will be used in while loop condition filter.&lt;br /&gt;Last function is stripping our slug by separators appearing at the beginning and end of slug. Because it uses many regexes I will leave in your hands work of decyphering it :)&lt;br /&gt;&lt;br /&gt;And now for some short sample usage :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;free = try_slug(self.instance, self.cleaned_data['slug'])&lt;br /&gt;if not free:&lt;br /&gt;    self.cleaned_data['slug'] = unique_slugify(self.instance, self.cleaned_data['slug'])&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-7870563899189156149?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/7870563899189156149/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/01/provide-unique-slugs-for-model-class.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/7870563899189156149'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/7870563899189156149'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2011/01/provide-unique-slugs-for-model-class.html' title='Provide unique slugs for model class'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-3898403785186410867</id><published>2010-12-09T22:56:00.000+01:00</published><updated>2010-12-10T15:53:21.022+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='python-twitter'/><category scheme='http://www.blogger.com/atom/ns#' term='twitter-api'/><category scheme='http://www.blogger.com/atom/ns#' term='parsing'/><category scheme='http://www.blogger.com/atom/ns#' term='twitter'/><title type='text'>Parsing tweets links, users and hash tags with django and python-twitter.</title><content type='html'>Hello again. Today I'm going to continue my previous &lt;a href="http://fromzerotocodehero.blogspot.com/2010/10/synchronising-django-with-twitter-using.html"&gt;post&lt;/a&gt; concerning django and twitter. Last time we've finished after synchronising with twitter. This time I'm gonna show you how to parse list of received tweets for rendering it in our template so that links,hash tags and users mentions are treated as clickable links. So here's the code, I've added some comments to clarify what we're doing currently:&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;def parse_tweets(tweets):&lt;br /&gt;    import re&lt;br /&gt;    &lt;br /&gt;    result = []&lt;br /&gt;    for tw in tweets:&lt;br /&gt;        tweet = tw.text;&lt;br /&gt;        #compile regexes as objects&lt;br /&gt;        hash_regex = re.compile(r'#[0-9a-zA-Z+_]*',re.IGNORECASE) &lt;br /&gt;        user_regex = re.compile(r'@[0-9a-zA-Z+_]*',re.IGNORECASE)&lt;br /&gt;        &lt;br /&gt;        #first deal with links. Any http://... string change to a proper link&lt;br /&gt;        tweet = re.sub('http://[^ ,]*', lambda t: "&lt;a href='%s'&gt;%s&lt;/a&gt;" % (t.group(0), t.group(0)), tweet)&lt;br /&gt;        &lt;br /&gt;        #for all elements matching our pattern...&lt;br /&gt;        for usr in user_regex.finditer(tweet):&lt;br /&gt;            &lt;br /&gt;            #for each whole match replace '@' with ''&lt;br /&gt;            url_tweet = usr.group(0).replace('@','')&lt;br /&gt;&lt;br /&gt;            #in tweet's text replace text with proper link, now without '@'&lt;br /&gt;            tweet = tweet.replace(usr.group(0),&lt;br /&gt;                '&lt;a href="http://twitter.com/'+url_tweet+'" title="'+usr.group(0)+'"&gt;'+usr.group(0)+'&lt;/a&gt;')&lt;br /&gt;&lt;br /&gt;        #do the same for hash tags&lt;br /&gt;        for hash in hash_regex.finditer(tweet):&lt;br /&gt;            url_hash = hash.group(0).replace('#','%23')&lt;br /&gt;            if len ( hash.group(0) ) &gt; 2:&lt;br /&gt;                tweet = tweet.replace(hash.group(0),&lt;br /&gt;                    '&lt;a href="http://search.twitter.com/search?q='+url_hash+'" title="'+hash.group(0)+'"&gt;'+hash.group(0)+'&lt;/a&gt;'); &lt;br /&gt;&lt;br /&gt;        #append each tweet to our list. Here I'm creating a dict containing tweet's text and date&lt;br /&gt;        posts.append({'tweet': tweet, 'date': s.pub_time})   &lt;br /&gt;    return posts&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And now to show it in template :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;&lt;ul&gt;{% for t in tweets %}&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;br /&gt;{% for k, v in t.items %}&lt;br /&gt;&lt;br /&gt;{% ifequal k 'summary' %}&lt;br /&gt;&lt;br /&gt;{{ v|safe }}&lt;br /&gt;&lt;br /&gt;{% else %}&lt;br /&gt;&lt;br /&gt;{% ifequal k 'date' %}&lt;br /&gt;&lt;br /&gt;&lt;span&gt;{{v|timesince}} ago&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;{% endifequal %}&lt;br /&gt;&lt;br /&gt;{% endifequal %}&lt;br /&gt;&lt;br /&gt;{% endfor %}&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;{% endfor %}     &lt;/ul&gt;&lt;/pre&gt;Probably there are better ways of doing this, but this one works for me. If you have any questions just write a comment or follow me via &lt;a href="http://twitter.com/#!/sasklacz"&gt;twitter&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-3898403785186410867?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/3898403785186410867/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/12/parsing-tweets-links-users-and-hash.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/3898403785186410867'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/3898403785186410867'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/12/parsing-tweets-links-users-and-hash.html' title='Parsing tweets links, users and hash tags with django and python-twitter.'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-9033953635114632840</id><published>2010-12-08T03:30:00.002+01:00</published><updated>2011-01-17T22:53:31.202+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='object'/><category scheme='http://www.blogger.com/atom/ns#' term='filter'/><category scheme='http://www.blogger.com/atom/ns#' term='django-template'/><category scheme='http://www.blogger.com/atom/ns#' term='variable'/><title type='text'>Check object's parameter value in django template</title><content type='html'>I'm just finishing probably the most complexed project I'll ever build in django, at least by myself. During the development I've encountered numerous problems, some of without satisfying solutions on the web. So now for the next few posts I will share the results of my research, thinking and developing. Topic for today is :&lt;br /&gt;&lt;br /&gt;&lt;b&gt;How to check value of object's parameters in a template ?&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Why do I ever need to do this kind of thing you may think. Yeah that's what I thought till now. But just think of my exact example - We have a site with some objects, that people can vote on. If someone has already voted we show him the result - if not, we render a voting button. Things are easy when rendering static page that is refreshed after each vote. But what if we need (just as I did) it to be dynamic ? I'm pretty sure that this problem can be solved using custom templatetag. But I've thought about a simpler solution using filters. So let's start.&lt;br /&gt;I have created a context processor storing IP address of user. In my template I'm returning list of objects in a for loop, and on each object I'm using my filter, with IP as parameter:&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;{{ submission|check_voting:IP_ADDRESS|safe }}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And now the filter part :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;@register.filter&lt;br /&gt;def check_voting(obj, ip):&lt;br /&gt;    result = obj.check_vote(ip)&lt;br /&gt;    if result:&lt;br /&gt;        result = "&lt;div class='votes-counter'&gt;%s votes&lt;/div&gt;" % obj.votes&lt;br /&gt;    else:&lt;br /&gt;        result =  "&lt;script src='http://connect.facebook.net/en_US/all.js#xfbml=1'&gt;&lt;/script&gt;&lt;fb:like layout='button_count' href='%s%s'&gt;&lt;/fb:like&gt;" % (settings.SITE_URL, obj.get_absolute_url() )    &lt;br /&gt;&lt;br /&gt;    return result&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;As you can see my filter takes two arguments - object on which it was called, and ip. Then I'm doing some processing on my object's method 'check_vote' that returns me boolean value depending on query result for vote by ip. According to it's value I'm either showing a facebook like button used for voting, or just plain vote counter.&lt;br /&gt;Hope you'll find this useful.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-9033953635114632840?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/9033953635114632840/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/12/check-objects-parameter-value-in-django.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/9033953635114632840'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/9033953635114632840'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/12/check-objects-parameter-value-in-django.html' title='Check object&apos;s parameter value in django template'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-4612753627671347034</id><published>2010-11-08T12:34:00.000+01:00</published><updated>2010-11-08T12:34:26.724+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='uniqueness'/><category scheme='http://www.blogger.com/atom/ns#' term='database'/><category scheme='http://www.blogger.com/atom/ns#' term='guuid'/><title type='text'>Providing uniqueness of different objects across one database</title><content type='html'>Recently I needed to add facebook comments box for different pages (which were showing models of different classes). All of them needed some unique ID, to provide unique comments for each object. So at first I was thinking about applying GUUID for the db, but it looked like overcomplicating the problem. So I came up with this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;class GUUID(models.Model):&lt;br /&gt;    guuid = models.PositiveSmallIntegerField(_(u"Dummy GUUID"), default=1)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;It's a dummy model class with only one field (set to 1, but you can use it to provide some additional functionality). Ok, but where's our uniqueness ? &lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;class Celebrity(BaseObject):&lt;br /&gt;    uniq = models.IntegerField(blank=False, editable=False)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here it is. Each model has a 'uniq' field set to integer field (u can use PositiveInteger if you want to). Then in save method of each object we add this :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;    def save(self, *args, **kwargs):&lt;br /&gt;        if not self.uniq:&lt;br /&gt;            guuid = GUUID()&lt;br /&gt;            guuid.save()&lt;br /&gt;            self.uniq = guuid.id            &lt;br /&gt;        super(Celebrity, self).save(*args, **kwargs)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now when we save object, we check fo existence of 'uniq' field. If it is null, then we create a new GUUID object and set it's id as the value of 'uniq'.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-4612753627671347034?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/4612753627671347034/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/11/providing-uniqueness-of-different.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4612753627671347034'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4612753627671347034'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/11/providing-uniqueness-of-different.html' title='Providing uniqueness of different objects across one database'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-2641327948524490336</id><published>2010-10-18T20:56:00.002+02:00</published><updated>2010-10-18T20:57:49.145+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='python-twitter'/><category scheme='http://www.blogger.com/atom/ns#' term='twitter-api'/><category scheme='http://www.blogger.com/atom/ns#' term='twitter'/><category scheme='http://www.blogger.com/atom/ns#' term='oauth'/><category scheme='http://www.blogger.com/atom/ns#' term='django-syncr'/><title type='text'>Synchronizing django with twitter using django-syncr</title><content type='html'>Ok so you have your first django powered application running (let me guess - CMS ? Blog ? :) ) and now you'd like to make it more "web 2.0"-ish by adding your twitter feeds. Althought I personally think this app is useless and dumb people who pay me think differently. So let's start. First you'll need some python's dependencies.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://github.com/simplegeo/python-oauth2"&gt;python-oauth2&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.google.com/p/python-twitter/source/checkout"&gt;python-twitter&lt;/a&gt; and stay alert, cause you need the latest build (so don't use easy_install as you'll get the deprecated 0.6 version)&lt;br /&gt;&lt;a href="http://code.google.com/p/django-syncr/"&gt;django-syncr&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Then go to &lt;a href="http://dev.twitter.com/"&gt;dev.twitter&lt;/a&gt; and (if you already haven't) register a new application. This will generate you "consumer_key" and "consumer_secret". Write them down. Now let's get back to our application. &lt;br /&gt;Iinstall both python dependencies but django-syncr add as an application in settings.INSTALLED_APPS. The reason for this is that you need to edit a bit of code, since currently available syncr does not support OAuth recently introduced on Twitter. Next either find "get_access_token.py" in python-twitter package, or download this function from sources and send somewhere within the scope of python. Before sending it though, open and edit :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'&lt;br /&gt;SIGNIN_URL        = 'https://api.twitter.com/oauth/authenticate'&lt;br /&gt;&lt;br /&gt;consumer_key    = None&lt;br /&gt;consumer_secret = None&lt;br /&gt;&lt;br /&gt;if consumer_key is None or consumer_secret is None:&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In place of consumer_key and consumer_secret insert proper (previously saved) values as strings. Save and close and execute it with :&lt;br /&gt;&lt;br /&gt;"python get_access_token.py run"&lt;br /&gt;&lt;br /&gt;You will get a unique link printed in the console, that you need to visit. Visit it and press "Enter". Now you will get two more values to store somewhere : "access_token_key" and "access_token_secret".&lt;br /&gt;&lt;br /&gt;Okay, now open syncr.app.tweet and change `__init__` function to this :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;def __init__(self, username, key, secret, token_key, token_secret):&lt;br /&gt;&lt;br /&gt;        self.username = username&lt;br /&gt;        self.api = twitter.Api(&lt;br /&gt;                            consumer_key=key, &lt;br /&gt;                            consumer_secret=secret, &lt;br /&gt;                            access_token_key=token_key,&lt;br /&gt;                            access_token_secret=token_secret)&lt;br /&gt;        self.user_cache = dict()&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here you can have different approach of course. You can hardcode your key values in it, add them to settings or send them each time when synchronizing with Twitter. Decision is up to you. Okay, last improvements to django-syncr. Open syncr.twitter folder, and edit models.py file. Here change Tweet.tweeter_id field from PositiveIntegerField to either IntegerField(if you're running &lt; 1.2) or BigIntegerField. We're finished with edits, so sync your database and add this code to the view/context_processor that will serve your tweets :&lt;pre class="python" name="code"&gt;&lt;br /&gt;&lt;br /&gt;#1. create TwitterSyncr object&lt;br /&gt;&lt;br /&gt;t = TwitterSyncr('twitter_username', &lt;br /&gt;&lt;br /&gt;'your_consumer_key',&lt;br /&gt;&lt;br /&gt;'your_consumer_secret',&lt;br /&gt;&lt;br /&gt;'your_access_token_key',&lt;br /&gt;&lt;br /&gt;'your_access_token_secret',)&lt;br /&gt;&lt;br /&gt;#2. synchronize your TwitterSyncr object with existing Twitter user&lt;br /&gt;&lt;br /&gt;t.syncUser('twitter_username')&lt;br /&gt;&lt;br /&gt;#3. get tweets for the Twitter user (so it will import tweets from Twitter to your DB)&lt;br /&gt;&lt;br /&gt;t.syncTwitterUserTweets('twitter_username')&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;#4. grab user from database and it's tweets&lt;br /&gt;&lt;br /&gt;user = TwitterUser.objects.get(screen_name="twitter_username")&lt;br /&gt;&lt;br /&gt;tweets = Tweet.objects.filter(user=user)&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And voila ! You have a list of your most recent tweets available. Of course you can limit the amount of parsed tweets with [:number].&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-2641327948524490336?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/2641327948524490336/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/10/synchronising-django-with-twitter-using.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/2641327948524490336'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/2641327948524490336'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/10/synchronising-django-with-twitter-using.html' title='Synchronizing django with twitter using django-syncr'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-744538293418075739</id><published>2010-10-11T18:08:00.001+02:00</published><updated>2010-10-18T13:51:17.345+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='dateutil'/><category scheme='http://www.blogger.com/atom/ns#' term='datetime'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='generator-expression'/><title type='text'>Recent months list  in django</title><content type='html'>After a while I'm back with hot new stuff for you and me :) Recently I needed to select blog entries from 5 consecutive months (counting from current) to my footer archive list. The biggest problem was with the range of months in different years. After a lot of struggle I've came across a python module (probably you will have it in your default setup) `dateutil`, which gives new functionality to date related functions. Ok, so let's get to the code. My function was added to context processors to provide me functionality across whole site. Then we build a date object from current date. Next step is to run a generator expression (which I will speak about some more in the future as they're one of the most important features of python language together with coroutines and generator functions) for a increasing range of months (you can also use a list comprehension here if you need some additional lists functionality or a generator function. but I've tried to keep it simple). This gives us a generator object so we create a dictionary of it, with years as keys and corresponding months as dates. Because this dictionary provides us with numbers only, I've added additional function to translate them to string months values (note the brilliant Python's switch-case funcionality) here shown with Polish dictionary.&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;from datetime import datetime&lt;br /&gt;from dateutil.relativedelta import relativedelta&lt;br /&gt;&lt;br /&gt;def get_blog_archive(request):&lt;br /&gt;    now = datetime.today()&lt;br /&gt;    first_month = datetime(now.year, now.month, 1)&lt;br /&gt;    previous_months = (first_month - relativedelta(months = months) for months in range(0, 5, 1))&lt;br /&gt;    &lt;br /&gt;    news_archive = {}&lt;br /&gt;    for pm in previous_months:&lt;br /&gt;        m = translate_month(pm.month)&lt;br /&gt;        if news_archive.has_key(pm.year):&lt;br /&gt;            news_archive[pm.year].append(m)&lt;br /&gt;        else:&lt;br /&gt;            news_archive[pm.year] = [m]&lt;br /&gt;    m = translate_month(current_month)&lt;br /&gt;    news_archive[current_year].append(m)&lt;br /&gt;    &lt;br /&gt;    return {'NEWS_ARCHIVE': news_archive,}&lt;br /&gt;&lt;br /&gt;def translate_month(month):&lt;br /&gt;    ret_month = ""&lt;br /&gt;    months = {&lt;br /&gt;            1: "Styczeń",&lt;br /&gt;            2: "Luty",&lt;br /&gt;            3: "Marzec",&lt;br /&gt;            4: "Kwiecień",&lt;br /&gt;            5: "Maj",&lt;br /&gt;            6: "Czerwiec",&lt;br /&gt;            7: "Lipiec",&lt;br /&gt;            8: "Sierpień",&lt;br /&gt;            9: "Wrzesień",&lt;br /&gt;            10: "Październik",&lt;br /&gt;            11: "Listopad",&lt;br /&gt;            12: "Grudzień",&lt;br /&gt;        }&lt;br /&gt;    ret_month = months.get(month)&lt;br /&gt;    return ret_month&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Okay this code is nice but not really functional, beacuse we get months names as String (here with utf-8 chars) and its troublesome to parse them as urls. So here's a bit more functional approach :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;    news_archive = []&lt;br /&gt;    for pm in previous_months:&lt;br /&gt;        d = datetime(pm.year,pm.month,1)&lt;br /&gt;        news_archive.append(d)&lt;br /&gt;    &lt;br /&gt;    return {'NEWS_ARCHIVE': news_archive,}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And now in our template we just parse with for loop through list elements.&lt;br /&gt;So that's all and stay tooned for some more advanced django examples. I'm doing a really big project right now but there's a ready shoutbox for django example, few implementations of django-registration, something about handling files and more :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-744538293418075739?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/744538293418075739/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/10/recent-months-list-in-django.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/744538293418075739'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/744538293418075739'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/10/recent-months-list-in-django.html' title='Recent months list  in django'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-1439893187576603280</id><published>2010-07-29T17:57:00.000+02:00</published><updated>2010-07-29T17:57:49.509+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='context-processors'/><title type='text'>Conditional context processor for authenticated users</title><content type='html'>Recently I needed a context processor to display friends of my logged user. Userprofile is the name for extended user model. Here's the code :&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;def friends_list(request):&lt;br /&gt;    try:&lt;br /&gt;        user = request.user&lt;br /&gt;    except User.DoesNotExist:&lt;br /&gt;        user = AnonymousUser()&lt;br /&gt;    &lt;br /&gt;    userprofile = None&lt;br /&gt;    try:&lt;br /&gt;        userprofile = UserProfile.objects.get(user=request.user)&lt;br /&gt;    except UserProfile.DoesNotExist:&lt;br /&gt;        pass&lt;br /&gt;    if userprofile:&lt;br /&gt;        friends = Friend.objects.filter(friend_of=userprofile)&lt;br /&gt;    else:&lt;br /&gt;        friends = {}&lt;br /&gt;    return {'friends': friends}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-1439893187576603280?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/1439893187576603280/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/07/conditional-context-processor-for.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/1439893187576603280'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/1439893187576603280'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/07/conditional-context-processor-for.html' title='Conditional context processor for authenticated users'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-6700629488083596260</id><published>2010-07-28T04:26:00.000+02:00</published><updated>2010-07-28T04:26:40.136+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='python lambda'/><title type='text'>Python's lambda</title><content type='html'>Because I don't quite get what and when python's lambda function's can be of any use - I did some research. Then I've found this sleek way of calling one lined function with unnamed parameter :&lt;br /&gt;&lt;pre class="python" name="code"&gt;&gt;&gt;&gt; (lambda x: x*2)(3)&lt;br /&gt;6&lt;br /&gt;&lt;/pre&gt;Pretty cool.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-6700629488083596260?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/6700629488083596260/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/07/pythons-lambda.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/6700629488083596260'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/6700629488083596260'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/07/pythons-lambda.html' title='Python&apos;s lambda'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-4244747992773212757</id><published>2010-07-27T23:43:00.001+02:00</published><updated>2010-07-27T23:50:47.547+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='jQuery'/><title type='text'>Scroll to top - the new way</title><content type='html'>Thing you will find useful at some point - how to scroll from random part of page to the top ? Here's a way how to obtain it with jQuery :&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;$(document).ready(function(){&lt;br /&gt;  $('a[href=#]').click(function(){&lt;br /&gt;    $.scrollTo(0,'slow');&lt;br /&gt;    return false;&lt;br /&gt;  });&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;But remember to include &lt;a href="http://plugins.jquery.com/project/ScrollTo"&gt;jQuery ScrollTo&lt;/a&gt; plugin in your imports. Now every link with hash as target will scroll your page back to the top with nice jquerish effect. Cooll huh ?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-4244747992773212757?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/4244747992773212757/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/07/scroll-to-top-new-way.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4244747992773212757'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4244747992773212757'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/07/scroll-to-top-new-way.html' title='Scroll to top - the new way'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-4725897731652724526</id><published>2010-07-02T14:05:00.000+02:00</published><updated>2010-07-02T14:05:33.796+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='collections'/><category scheme='http://www.blogger.com/atom/ns#' term='arrays'/><title type='text'>Random sort of array elements</title><content type='html'>Recently I came across problem of sorting randomly elements of some array. Here's what I came up with :&lt;br /&gt;Pseudocode :&lt;br /&gt;&lt;br /&gt;for each element in the array&lt;br /&gt;  calculate a random number with index range from 0 to array size -1&lt;br /&gt;  store the current element in a temporary variable&lt;br /&gt;  replace the current element in the array with the element at the random index &lt;br /&gt;  replace the element at random index with the element at temporary variable&lt;br /&gt;&lt;br /&gt;Solution :&lt;br /&gt;&lt;pre class="java" name="code"&gt;        int[] buttons = new int[16];&lt;br /&gt;&lt;br /&gt;        for(int i=0; i&lt;16; i++){&lt;br /&gt;            buttons[i] = i;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        int rand;&lt;br /&gt;        int temp;&lt;br /&gt;        Random random;&lt;br /&gt;&lt;br /&gt;        random = new Random(System.currentTimeMillis());&lt;br /&gt;        for (int i = 0; i &lt; buttons.length; i++) {&lt;br /&gt;            rand = (random.nextInt() &amp; 0x7FFFFFFF) % buttons.length;&lt;br /&gt;            temp = buttons[i];&lt;br /&gt;            buttons[i] = buttons[rand];&lt;br /&gt;            buttons[rand] = temp;&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-4725897731652724526?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/4725897731652724526/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/07/random-sort-of-array-elements.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4725897731652724526'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4725897731652724526'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/07/random-sort-of-array-elements.html' title='Random sort of array elements'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-4366005097152606000</id><published>2010-06-11T00:35:00.000+02:00</published><updated>2010-06-11T00:35:28.666+02:00</updated><title type='text'>Threads in Java</title><content type='html'>"Dining Philosophers" problem solved with Java and Semaphores.&lt;br /&gt;&lt;br /&gt;&lt;pre class="java" name="code"&gt;import java.util.concurrent.Semaphore;&lt;br /&gt;import java.util.Random;&lt;br /&gt;import java.util.Vector;&lt;br /&gt;&lt;br /&gt;public class Philosopher extends Thread&lt;br /&gt;{&lt;br /&gt;    private static final Random rand = new Random();&lt;br /&gt;    private static int event=0;&lt;br /&gt;    private static String binary="";&lt;br /&gt;    private int id;&lt;br /&gt;    private Semaphore sem;&lt;br /&gt;    private static Vector&lt;Object[]&gt; vector = new Vector&lt;Object[]&gt;();&lt;br /&gt;&lt;br /&gt;    public Philosopher(int i, Semaphore s)&lt;br /&gt;    {&lt;br /&gt;        id = i;&lt;br /&gt;        sem = s;&lt;br /&gt;        binary = binary + "0";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void busy()&lt;br /&gt;    {&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            sleep(rand.nextInt(1000));&lt;br /&gt;        } catch (InterruptedException e){}&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void thinking()&lt;br /&gt;    {&lt;br /&gt;        String str = "Philosopher " + id + " is thinking";&lt;br /&gt;        vector.add( this.addToObject(System.currentTimeMillis(), event , str) );&lt;br /&gt;        event++;&lt;br /&gt;        busy();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void eating()&lt;br /&gt;    {&lt;br /&gt;        String str ="Philosopher " + id + " is hungry and is trying to pick up his chopsticks";&lt;br /&gt;        vector.add( this.addToObject(System.currentTimeMillis(), event , str) );&lt;br /&gt;        event++;&lt;br /&gt;        busy();&lt;br /&gt;        str = "Philosopher " + id + " is eating";&lt;br /&gt;        this.oneToBinary(id);&lt;br /&gt;        vector.add( this.addToObject(System.currentTimeMillis(), event , str) );&lt;br /&gt;        event++;&lt;br /&gt;        busy();&lt;br /&gt;        str = "Philosopher " + id + " finished eating, and puts away his chopsticks";&lt;br /&gt;        this.zeroToBinary(id);&lt;br /&gt;        vector.add( this.addToObject(System.currentTimeMillis(), event , str) );&lt;br /&gt;        event++;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private Object[] addToObject(long t, int i,String s ){&lt;br /&gt;        Object[] o = new Object[4];&lt;br /&gt;        o[3] = s;&lt;br /&gt;        o[2] = i;&lt;br /&gt;        o[1] = binary;&lt;br /&gt;        o[0] = t;&lt;br /&gt;        return o;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void oneToBinary(int i){&lt;br /&gt;        binary = binary.substring(0,i) + "1" + binary.substring(i+1);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void zeroToBinary(int i){&lt;br /&gt;        binary = binary.substring(0,i) + "0" + binary.substring(i+1);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public void run()&lt;br /&gt;    {&lt;br /&gt;        for (int i = 0; i &lt; 10; ++i)&lt;br /&gt;        {&lt;br /&gt;            thinking();&lt;br /&gt;            try&lt;br /&gt;            {&lt;br /&gt;                sem.acquire();&lt;br /&gt;            } catch (InterruptedException e){}&lt;br /&gt;            eating();&lt;br /&gt;            sem.release();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void main(String[] args)&lt;br /&gt;    {&lt;br /&gt;        final int N = 5;&lt;br /&gt;        Semaphore sem = new Semaphore(N, true);&lt;br /&gt;        Philosopher[] philosopher = new Philosopher[N];&lt;br /&gt;&lt;br /&gt;        // Start the philosophers&lt;br /&gt;        for (int i = 0; i &lt; N; i++) {&lt;br /&gt;          philosopher[i] = new Philosopher(i, sem);&lt;br /&gt;          philosopher[i].start();&lt;br /&gt;        }&lt;br /&gt;        // Wait for them to finish&lt;br /&gt;        for (int i = 0; i &lt; N; i++) {&lt;br /&gt;          try {&lt;br /&gt;            philosopher[i].join();&lt;br /&gt;          } catch(InterruptedException ex) {&lt;br /&gt;            return;&lt;br /&gt;          }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        for (int i = 0; i &lt; vector.size(); i++) {&lt;br /&gt;            Object[] o = vector.get(i);&lt;br /&gt;            System.out.printf("%d %d %s %s\n", o[0], o[2], o[1], o[3]);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-4366005097152606000?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/4366005097152606000/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/06/threads-in-java.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4366005097152606000'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4366005097152606000'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/06/threads-in-java.html' title='Threads in Java'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-2322814350371191955</id><published>2010-06-08T00:13:00.000+02:00</published><updated>2010-06-08T00:13:20.490+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='pointers'/><category scheme='http://www.blogger.com/atom/ns#' term='cpp'/><title type='text'>Tip of the Day #2 - pointers</title><content type='html'>Remember&lt;br /&gt;&lt;pre class="cpp" name="code"&gt;int* ptr;&lt;br /&gt;*ptr = 10;&lt;br /&gt;#but&lt;br /&gt;ptr = new int;&lt;br /&gt;#without ampersand and dereference !!&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-2322814350371191955?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/2322814350371191955/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/06/tip-of-day-2-pointers.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/2322814350371191955'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/2322814350371191955'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/06/tip-of-day-2-pointers.html' title='Tip of the Day #2 - pointers'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-5936751296564201925</id><published>2010-06-07T21:14:00.000+02:00</published><updated>2010-06-07T21:14:39.852+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='pointers'/><category scheme='http://www.blogger.com/atom/ns#' term='cpp'/><title type='text'>Constant pointers, pointers to constants ?</title><content type='html'>What is the difference between:&lt;br /&gt;&lt;pre class="cpp" name="code"&gt;float fVar = 3.14;&lt;br /&gt;const float* ptr1 = &amp;fVar;&lt;br /&gt;&lt;/pre&gt;and:&lt;br /&gt;&lt;pre class="cpp" name="code"&gt;float fVar = 3.14;&lt;br /&gt;float* const ptr2 = &amp;fVar;&lt;br /&gt;&lt;/pre&gt;? The first one is pointer to constant value, so we can't change the value of variable the pointer points to :&lt;br /&gt;&lt;pre class="cpp" name="code"&gt;*ptr1 = 10;&lt;br /&gt;&lt;/pre&gt;The second one in contrary is a constant pointer to a value, and because of that we can't readdress it to point at different variable :&lt;br /&gt;&lt;pre class="cpp" name="code"&gt;float fVar2;&lt;br /&gt;*ptr2 = &amp;fVar2;&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-5936751296564201925?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/5936751296564201925/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/06/constant-pointers-pointers-to-constants.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/5936751296564201925'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/5936751296564201925'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/06/constant-pointers-pointers-to-constants.html' title='Constant pointers, pointers to constants ?'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-510770876925079570</id><published>2010-06-03T01:56:00.000+02:00</published><updated>2010-06-03T01:56:00.510+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django-contrib'/><category scheme='http://www.blogger.com/atom/ns#' term='django'/><title type='text'>Django Contrib Revealed - Flatpages</title><content type='html'>Very often while creating big portals there are static pages just wasting your time to be created. Django has a solution for this problem also - the Flatpages application inside Contribution package. This application allows you to manage such static pages from django-admin, and it let's you create templates using Django's template system. How to get started ?&lt;br /&gt;- Add 'django.contrib.flatpages' to INSTALLED_APPS. Also you need to have django.contrib.sites activated since flatpages depend on this package.&lt;br /&gt;- Add 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware' to MIDDLEWARE_CLASSES.&lt;br /&gt;This is how the flatpage model looks like :&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django.db import models&lt;br /&gt;from django.contrib.sites.models import Site&lt;br /&gt;&lt;br /&gt;class FlatPage(models.Model):&lt;br /&gt;    url = models.CharField(max_length=100, db_index=True)&lt;br /&gt;    title = models.CharField(max_length=200)&lt;br /&gt;    content = models.TextField(blank=True)&lt;br /&gt;    enable_comments = models.BooleanField()&lt;br /&gt;    template_name = models.ChorField(max_length=70, blank=True)&lt;br /&gt;    registration_required = models.BooleanField()&lt;br /&gt;    sites = models.ManyToManyField(Site)&lt;br /&gt;&lt;/pre&gt;Okay so everything looks clear here I guess. For every flatpage we can specify either custom template, or use flatpages/default.html template (still creating the default template is also our responsibility !). Flatpage templates get a single context variable passed - flatpage, so we can use the Flatpage object's fields ie. {{ flatpage.title }}, {{ flatpage.content }}. Simple, but can spare lots of time :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-510770876925079570?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/510770876925079570/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/06/django-contrib-revealed-flatpages.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/510770876925079570'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/510770876925079570'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/06/django-contrib-revealed-flatpages.html' title='Django Contrib Revealed - Flatpages'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-5006820298262685482</id><published>2010-05-28T01:42:00.000+02:00</published><updated>2010-05-28T01:42:25.748+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django-contrib'/><category scheme='http://www.blogger.com/atom/ns#' term='django'/><title type='text'>Django Contrib Revealed - Sites</title><content type='html'>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 ? &lt;br /&gt;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.&lt;br /&gt;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 ?&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django.db import models&lt;br /&gt;from django.contrib.sites.models import Site&lt;br /&gt;from django.contrib.sites.managers import currentSiteManager&lt;br /&gt;&lt;br /&gt;class News(models.Model):&lt;br /&gt;    title = models.CharField(max_length=100)&lt;br /&gt;    # ...&lt;br /&gt;    site = models.ForeignKey(Site)&lt;br /&gt;    objects = models.Manager()&lt;br /&gt;    current_site = CurrentSiteManager()&lt;br /&gt;&lt;/pre&gt;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 :&lt;br /&gt;current_site = CurrentSiteManager('site_related_field')&lt;br /&gt;And now for the views :&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django.conf.import settings&lt;br /&gt;&lt;br /&gt;def simple_view(request):&lt;br /&gt;    if settings.SITE_ID == 1:&lt;br /&gt;        # code here&lt;br /&gt;    else:&lt;br /&gt;        # code here&lt;br /&gt;&lt;/pre&gt;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() :&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django.contrib.sites.models import Site&lt;br /&gt;&lt;br /&gt;def simple_view(request):&lt;br /&gt;    current_site = Site.objects.get_current()&lt;br /&gt;    #here we're using one of Site models field - domain.&lt;br /&gt;    if current_site.domain == 'example.com':&lt;br /&gt;        #code here&lt;br /&gt;    else:&lt;br /&gt;        # code here&lt;br /&gt;&lt;/pre&gt;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 :&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django.conf import settings&lt;br /&gt;from django.contrib.sites.models import Site&lt;br /&gt;&lt;br /&gt;def simple_view(request):&lt;br /&gt;    current_site = Site.objects.get(id=settings.SITE_ID)&lt;br /&gt;    #here we're using one of Site models field - domain.&lt;br /&gt;    if current_site.id == 1:&lt;br /&gt;        #code here&lt;br /&gt;    else:&lt;br /&gt;        # code here&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-5006820298262685482?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/5006820298262685482/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/django-contrib-revealed-sites.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/5006820298262685482'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/5006820298262685482'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/django-contrib-revealed-sites.html' title='Django Contrib Revealed - Sites'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-4261865621396289746</id><published>2010-05-27T01:12:00.001+02:00</published><updated>2010-05-29T00:56:07.683+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='parsing'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='string'/><title type='text'>Parsing string</title><content type='html'>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 :&lt;br /&gt;&lt;br /&gt;"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"&lt;br /&gt;&lt;br /&gt;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 :&lt;br /&gt;&lt;pre class="python" name="code"&gt;#note using fsum to preserve float loss&lt;br /&gt;fsum(float(n) for n in str.replace(',','.').split())&lt;br /&gt;&lt;/pre&gt;And here's second solution, since ',' is a legitimate decimal point for many people. &lt;br /&gt;&lt;pre class="python" name="code"&gt;import locale&lt;br /&gt;locale.setlocale(0,"po")&lt;br /&gt;sum(map(locale.atof, s.split()))&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-4261865621396289746?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/4261865621396289746/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/parsing-string.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4261865621396289746'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/4261865621396289746'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/parsing-string.html' title='Parsing string'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-9164158223531399421</id><published>2010-05-26T00:30:00.000+02:00</published><updated>2010-05-26T00:30:10.504+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='urls'/><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='views'/><category scheme='http://www.blogger.com/atom/ns#' term='generic-views'/><title type='text'>Generic views part 1</title><content type='html'>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 :&lt;br /&gt;&lt;pre class="python" name="code"&gt;from django.conf.urls.defaults import *&lt;br /&gt;from django.views.generic.simple import direct_to_template&lt;br /&gt;&lt;br /&gt;urlpatterns = patterns('',&lt;br /&gt;      (r'^/$', direct_to_template, { 'template': 'index.html' })&lt;br /&gt;)&lt;br /&gt;&lt;/pre&gt;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...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-9164158223531399421?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/9164158223531399421/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/generic-views-part-1.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/9164158223531399421'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/9164158223531399421'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/generic-views-part-1.html' title='Generic views part 1'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-5511550107277083272</id><published>2010-05-25T14:28:00.000+02:00</published><updated>2010-05-25T19:06:24.297+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='collections'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='operators'/><title type='text'>Tip of the Day #1 - in or not ?</title><content type='html'>I really love those small python's built in functions and operators. How to check if variable is in some collection ?&lt;br /&gt;&lt;br /&gt;&lt;pre class="python" name="code"&gt;&gt;&gt;&gt; z = x in s&lt;br /&gt;&gt;&gt;&gt; z&lt;br /&gt;True&lt;br /&gt;&lt;/pre&gt;z will return True if x is in s. Isn't that cool or what ?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-5511550107277083272?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/5511550107277083272/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/tip-of-day-1-in-or-not.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/5511550107277083272'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/5511550107277083272'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/tip-of-day-1-in-or-not.html' title='Tip of the Day #1 - in or not ?'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-2866476900041854254</id><published>2010-05-25T00:21:00.000+02:00</published><updated>2010-05-25T14:27:46.042+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='urls'/><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='redundancy'/><title type='text'>Faking URL values</title><content type='html'>Let's say we have a shop, with product urls looking like this:&lt;br /&gt;&lt;br /&gt;http://myshop.com/motorbikes/choppers&lt;br /&gt;http://myshop.com/bikes/bmx&lt;br /&gt;http://myshop.com/skates/aggresive&lt;br /&gt;&lt;br /&gt;But also we have a page for top selling products:&lt;br /&gt;&lt;br /&gt;http://myshop.com/topsellers&lt;br /&gt;&lt;br /&gt;, that uses the same view:&lt;br /&gt;&lt;pre class="python" name="code"&gt;def products_list(request, parent_category, child_category):&lt;br /&gt;&lt;/pre&gt;How we can avoid writing another view for top sellers, that don't send either parent_ or child_ categories in URL's ?&lt;br /&gt;&lt;pre class="python" name="code"&gt;urlpatterns = patterns('',&lt;br /&gt;    (r'^topsellers/$', views.products_list, {'parent_category': 'topsellers', 'child_category': 'topsellers'}),&lt;br /&gt;    (r'^(?P&lt;parent_category/&gt;\w)/(?P&lt;/child_category/&gt;\w)/$', views.products_list),&lt;br /&gt;)&lt;br /&gt;&lt;/pre&gt;&lt;/parent_category&gt;&lt;/child_category&gt;&lt;br /&gt;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 ).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-2866476900041854254?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/2866476900041854254/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/fakking-url-values.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/2866476900041854254'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/2866476900041854254'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/fakking-url-values.html' title='Faking URL values'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-8660768605256417109</id><published>2010-05-22T15:53:00.000+02:00</published><updated>2010-05-22T15:57:00.413+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='django'/><category scheme='http://www.blogger.com/atom/ns#' term='context-processors'/><category scheme='http://www.blogger.com/atom/ns#' term='settings'/><title type='text'>Don't add unnecessary Context Processors</title><content type='html'>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 ?&lt;br /&gt;&lt;br /&gt;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 :&lt;br /&gt;&lt;pre class="python" name="code"&gt;def user(request):&lt;br /&gt;    if hasattr(request, 'user'):&lt;br /&gt;        return {'user':request.user }&lt;br /&gt;    return {}&lt;br /&gt;&lt;/pre&gt;?&lt;br /&gt;&lt;br /&gt;Let's just take a look at our settings.py file. By default (in Django 1.2) TEMPLATE_CONTEXT_PROCESSORS variable looks like this :&lt;br /&gt;&lt;br /&gt;TEMPLATE_CONTEXT_PROCESSORS = (&lt;br /&gt;"django.contrib.auth.context_processors.auth",&lt;br /&gt;"django.core.context_processors.debug",&lt;br /&gt;"django.core.context_processors.i18n",&lt;br /&gt;"django.core.context_processors.media",&lt;br /&gt;"django.contrib.messages.context_processors.messages"&lt;br /&gt;)&lt;br /&gt;&lt;br /&gt;And looking into documentation we can find :&lt;br /&gt;&lt;br /&gt;"user -- An auth.User instance representing the currently logged-in user (or an AnonymousUser  instance, if the client isn't logged in)."&lt;br /&gt;&lt;br /&gt;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 settings.py once again and insert this line :&lt;br /&gt;&lt;br /&gt;AUTH_PROFILE_MODULE = 'accounts.UserProfile',&lt;br /&gt;&lt;br /&gt;where 'accounts' is the name of the app where you're storing your extended model. And now as Django Docs say :&lt;br /&gt;&lt;br /&gt;"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."&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-8660768605256417109?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/8660768605256417109/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/dont-add-unnecessary-context-processors.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/8660768605256417109'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/8660768605256417109'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/dont-add-unnecessary-context-processors.html' title='Don&apos;t add unnecessary Context Processors'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-7725702810350626482</id><published>2010-05-20T00:28:00.000+02:00</published><updated>2010-05-22T15:07:22.431+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='cpp'/><title type='text'>Beginning C++</title><content type='html'>Two solutions for counting average of x &amp;lt; 100 numbers.  &lt;br /&gt;#1 &lt;br /&gt;&lt;pre class="cpp" name="code"&gt;int tab100];&lt;br /&gt;    int n=0;&lt;br /&gt;    int number=0;&lt;br /&gt;    char input[10];&lt;br /&gt;&lt;br /&gt;    while (n++ &amp;lt; 100)&lt;br /&gt;    {     &lt;br /&gt;       cout &amp;lt;&amp;lt; "Give " &amp;lt;&amp;lt; n &amp;lt;&amp;lt; " number : ";&lt;br /&gt;       memset(input, 0x00, 10);&lt;br /&gt;       cin.getline(input, 10);&lt;br /&gt;       number = atoi(input);&lt;br /&gt;       if (number &amp;gt; 0)&lt;br /&gt;           tab[n-1] = number;&lt;br /&gt;       else&lt;br /&gt;           break;&lt;br /&gt;    }&lt;br /&gt;    cout &amp;lt;&amp;lt; average(tab, n-1) &amp;lt;&amp;lt; endl; &lt;br /&gt;    getch(); &lt;br /&gt;    return 0;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;#2&lt;br /&gt;&lt;pre class="c" name="code"&gt;int main()&lt;br /&gt;{&lt;br /&gt;    const size_t COUNT = 100;&lt;br /&gt;    int tab[COUNT];&lt;br /&gt;    size_t n;   &lt;br /&gt;&lt;br /&gt;    cin.tie(&amp;amp;cout);&lt;br /&gt;&lt;br /&gt;    for (n = 0; n &amp;lt; COUNT; ++n ) {&lt;br /&gt;        cout &amp;lt;&amp;lt; "Give " &amp;lt;&amp;lt; n+1 &amp;lt;&amp;lt; " number : ";&lt;br /&gt;        cin &amp;gt;&amp;gt; tab[n];&lt;br /&gt;&lt;br /&gt;        if (!cin)&lt;br /&gt;            break;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    if (n &amp;gt; 0)&lt;br /&gt;        cout &amp;lt;&amp;lt; average(tab, n) &amp;lt;&amp;lt; endl;&lt;br /&gt;    &lt;br /&gt;    getch();&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Which one do you prefer ?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-7725702810350626482?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/7725702810350626482/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/two-solutions-for-counting-average-of-x.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/7725702810350626482'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/7725702810350626482'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/two-solutions-for-counting-average-of-x.html' title='Beginning C++'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-1961038197593604730</id><published>2010-05-19T09:27:00.000+02:00</published><updated>2010-05-19T09:28:15.740+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='functions'/><title type='text'>Python's all() function usage.</title><content type='html'>Recently I've came across superb python function all(). What it does is just selecting all items,variables,objects,etc fulfilling some requirements. Usage :&lt;br /&gt;&lt;br /&gt;all(our_requirement)&lt;br /&gt;&lt;br /&gt;Here's my code from Django-LFS (used on &lt;a href="http://purple-cow.pl"&gt;purple-cow.pl&lt;/a&gt; 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.    &lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="python"&gt;def deactivate(self):&lt;br /&gt;        """If there are no stocks, deactivate the product. Used in last step of checkout.&lt;br /&gt;        """&lt;br /&gt;&lt;br /&gt;        inactive = False&lt;br /&gt;        &lt;br /&gt;        if self.is_variant():&lt;br /&gt;            prod = self.parent&lt;br /&gt;            inactive = all(var.get_stock_amount() == 0 for var in prod.variants.filter(active=True))&lt;br /&gt;            if inactive:&lt;br /&gt;                prod.active = 0&lt;br /&gt;            prod.save()&lt;br /&gt;        else:&lt;br /&gt;            if self.get_stock_amount() == 0:&lt;br /&gt;                self.active = 0&lt;br /&gt;        &lt;br /&gt;            self.save()&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-1961038197593604730?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/1961038197593604730/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/pythons-all-function-usage.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/1961038197593604730'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/1961038197593604730'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/pythons-all-function-usage.html' title='Python&apos;s all() function usage.'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7456076804996318821.post-7238123834042671307</id><published>2010-05-19T02:42:00.000+02:00</published><updated>2010-05-19T08:56:19.562+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='dictionary'/><category scheme='http://www.blogger.com/atom/ns#' term='lists'/><title type='text'>[Python] Joining two lists in a dictionary</title><content type='html'>Hello and welcome everybody.&lt;br /&gt;First entry, so something pythonic for starters. Simple function for joining two lists in a dictionary. If anyone has better idea, leave a comment.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="python"&gt;&lt;br /&gt;def mapper(keys, values):&lt;br /&gt;  n = len(keys)&lt;br /&gt;  return [dict(zip(keys, values[i:i + n]))&lt;br /&gt;  for i in range(0, len(values), n)]&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7456076804996318821-7238123834042671307?l=fromzerotocodehero.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fromzerotocodehero.blogspot.com/feeds/7238123834042671307/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/blogger-syntax-highlight.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/7238123834042671307'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7456076804996318821/posts/default/7238123834042671307'/><link rel='alternate' type='text/html' href='http://fromzerotocodehero.blogspot.com/2010/05/blogger-syntax-highlight.html' title='[Python] Joining two lists in a dictionary'/><author><name>owca</name><uri>http://www.blogger.com/profile/12892966621806011632</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
