07
Oct

As Espanhas

A Espanha está cada vez mais dividida. No mês passado vi a notícia do país basco a tentar fazer um referendo para ser tornar independente. Hoje reparei que a Catalunha já tem um domínio de topo na internet, o .cat. E pelos vistos a Galiza está na lista de espera para ter o seu domínio de topo, o .gal (e depois alguém vai registar o portu.gal :-).

E eu acho bem. A verdadeira liberdade de uma população é poder rejeitar a própria organização que lhe dá a liberdade. Mas ainda estou para ver se Madrid vai deixar.

05
Oct

Including variables as templates

To manage the website content in a flexible way it's practical to have some portions of some pages generated from variables created as FlatPages. For example, in a frontpage I have a "featured item" section which renders a flatpage variable.

def frontpage(request):
    fp = FlatPage.objects.get(url='featured')
    return render_to_response('frontpage.html', {'fp':fp })
then in the template
...<div id="featured">{{ fp.content }}</div> ...

But sometimes it would also be nice to put some template tags inside those flatpages. Django does not seem to provide a tag for such task (most probably because it can be a bad idea from the security point of view), but the ssi tag does exactly the same thing for files in the filesystem. Based on ssi, the code bellow defines a new tag that includes the content of a variable as a template.

def do_templatevar(parser, token):
    bits = token.contents.split()
    if len(bits) != 2:
        raise TemplateSyntaxError, "%s tag takes one argument" % bits[0]
    return TemplateVarNode(parser.compile_filter(bits[1]))

register.tag('templatevar', do_templatevar)

class TemplateVarNode(Node):
    def __init__(self, content):
        self.content = content

    def render(self, context):
        content = self.content.resolve(context)
        try:
            t = Template(content)
            return t.render(context)
        except TemplateSyntaxError, e:
            if settings.DEBUG:
                return "[Included template had syntax error: %s]" % e
            else:
                return '' # Fail silently

Now I can put the following code in my flat page

<p>This is my media_url: {{ MEDIA_URL }}</p>

And it will work if I define my template as

...<div id="featured">{% templatevar fp.content %}</div> ...

A last remark to mention databasetemplateloader that allows to load template data from the database. I never tried it, but seems to be a more generic solution (and also a way to have a Zope 1 experience in Django).

01
Oct

OpenID blog claim in technorati

This is probably old news but the openid blog claim in technorati is definitely a very good idea. If your blog is also your openid, when doing the blog claim in technorati you are given the chance to do the claim using openid.

With this option you just have to authenticate in your openid provider and ... it's done!

Just by having these two lines in my blog header allowed technorati to give me an easy authentication process.

<link rel="openid.server" href="http://www.myopenid.com/server">
<link rel="openid.delegate" href="http://pedrolima.myopenid.com/">

I was happily surprised with this process. Simple and easy.

29
Sep

Media URL on javascript files

Using the MEDIA_URL setting in a template context variable is a very practical way to have the media files being served from a location defined in the settings file. James Bennett explains here how to define and use this context variable.

But, for example, if I need to have media urls in my javascript files, which are static files, I don't have access to this variable. Take this very simple example. I have a image placeholder in the markup.

<h1>Test 01</h1>
<img id="placeholder" src="">

And the image url is set with javascript.

function set_image() {
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src","http://localhost:8000/static/django.gif");
}
window.onload = set_image

In this case the full url is hardcoded which, of course is not what I want. Like for the other media files I want to use the above url during development and in deployment switch to the media server url. Something like:

http://media.someserver.com/django.gif

I discuss bellow the approaches I have been trying.

Always use the media server urls in the javascript

Just always using the media server url in the javascript files. It's simple and works fine if I don't need to change the static resources. But changing the static files during development becomes a problem. And developing offline it's also a problem. So it's not a good solution.

Global javascript variable with the media url

This means having the following code in the base template.

<script src="{{ media_url }}test.js" type="text/javascript"></script>
<script language="javascript">var MEDIA_URL = "{{ MEDIA_URL }}";</script>

and in the javascript

function set_image() {
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src", MEDIA_URL + "django.gif");
}

This approach works, and I consider it more practical than the previous one, but to have a global variable and extra markup is not very clean.

Media url stored in a meta tag

As a variant of the previous approach, instead of creating a global javascript variable I set a meta tag with the location of the media_url.

<meta name="media_url" id="media_url" content="{{ MEDIA_URL }}" />

Then in the javascript file extract the value from the DOM.

document.getElementById("media_url").getAttribute("content");

Again it's not a very clean solution.

Take the media url from the CSS url

This last one is based on convention. I always have the CSS files in the root of my media folder. If the urls for my CSS files are like:

http://media.someserver.com/style.css

then my media url is

http://media.someserver.com/

So in this case the idea is to always fetch the media url from the CSS file url (and so the document must always have a CSS file). The javascript function for such task:

function get_media_url() {
    var css_url = document.styleSheets[0].href;
    var last_slash = css_url.lastIndexOf('/');
    return css_url.substr(0,last_slash+1);
}

Although being based on convention this last one is the one I am more keen on using.

But to be honest, one of the reasons to write this post was to try to find some best practice for this topic. And maybe (hopefully) someone from the community can show some better practice.

26
Sep

OpenID

A principal razão para criar este blog foi a necessidade de migrar as coisas que guardava no meu espaço do freezope.org. Esse serviço já estava abandonado há algum tempo e recentemente parece que desligou mesmo.

Não me posso queixar, pois aquilo era gratuito e funcionou muito bem durante muito tempo. É claro que sem um business model era de esperar que mais cedo ou mais tarde aquilo fechasse.

Um bonus de fazer um blog próprio foi o de ficar com um username próprio para o OpenID. Com o OpenID podemos efectuar o login num site que suporte este formato sem ter que criar uma password nesse site. Já tinha um OpenID no myopenid.com, mas um dos riscos graves do OpenID é que se o servidor que guarda a identidade fôr desligado ficamos sem poder entrar em todos os sites em que nos identificamos com o Openid.

Mas tendo um domínio próprio é fácil tornar o nosso domínio a nossa identidade (estas instruções mostram como fazer), e delegar a tarefa de identificação a um dos muitos serviços que existem. Se por azar o serviço que usamos desaparecer apenas temos que criar uma nova conta num novo serviço e mudar a regra de delegação.

Ou seja, tornei o URL deste site a minha identidade OpenID.