Skip navigation.

Django & Tangos

Baby steps to a lovely web

Firefox redirects to localhost.com

Now, when there's a problem about my django application and try to access it (I use port 80 as default to my runserver) firefox insists of redirecting to localhost.com
So annoying

So I found this trick:

in firefox type about:config and change the setting for:

browser.fixup.alternate.enabled to false



thanks duckworth


be aware, no more redirects in firefox

thanks google =P

Custom filter on django admin

,

We had to have a custom queryset for a model in Admin so we could have only the active records.
A teammate got it work by doing a new FilterSpec and I had to use it in another model.

First of all, create the FilterSpec for your admin:

customfilterspec.py

# -*- coding: utf-8 -*-

from django.db import models
from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec, RelatedFilterSpec
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _

class CustomFilterSpec(FilterSpec):
    """
    Na verdade este é um FilterSpec para passar Queryset diferente do default do campo, por exemplo, filtrado 
    """
    def __init__(self, f, request, params, model, model_admin):
        super(CustomFilterSpec, self).__init__(f, request, params, model, model_admin)
        self.lookup_val = request.GET.get(f.name, None)
        if isinstance(f, models.ManyToManyField):
            self.lookup_title = f.rel.to._meta.verbose_name
        else:
            self.lookup_title = f.verbose_name
        
        # Queryset padrão
        qs = f.rel.to._default_manager.all()
        
        # Verifica se as opções do admin possuem um queryset para este campo
        qs_dict = getattr(model_admin, 'custom_filter_spec', None)
        if qs_dict and f.name in qs_dict:
            qs = qs_dict[f.name]
        
        self.lookup_choices = qs.all()

    def title(self):
        return self.lookup_title

    def choices(self, cl):
        yield {'selected': self.lookup_val is None,
               'query_string': cl.get_query_string({}, [self.field.name]),
               'display': All}
        for inst in self.lookup_choices:
            val = smart_unicode(inst.pk)
            yield {'selected': self.lookup_val == val,
                   'query_string': cl.get_query_string({self.field.name: val}),
                   'display': smart_unicode(inst)}

# O ideal seria usar o método register, mas o filtro ficaria por último e não seria utilizável.
# Então é preciso registrá-lo como primeiro.
#FilterSpec.register(lambda f: bool(f.rel and hasattr(f, 'custom_filter_spec')), CustomFilterSpec)
FilterSpec.filter_specs.insert(0, (lambda f: bool(f.rel and hasattr(f, 'custom_filter_spec')), CustomFilterSpec))



Save the file and put it somewhere in your app to import later

It must be loaded at least once so the filter will be added to the list, I recommend put it in an admin.py file.

so, on top of your admin.py:

from utils.customfilterspec import CustomFilterSpec



Then you must prepare your model to assure that the field can use FilterSpec¹

So, in your model do:

class MyModel(models.Model):
   created_by = models.ForeignKey(User)
   ...
   created_by.custom_filter_spec = True




And finally, in your Admin class you must include this field as a list_filter and give a resultset to it:

class MyAdminOptions(ModelAdmin):
   ...
   list_filter = ('created_by',)
   custom_filter_spec = {'created_by': User.objects.filter(is_staff=True).order_by('username')}



So now, in my example, I can filter only by staff user in my admin page.

Hope it helps

obs:
1: This models stuff is set in CustomFilterSpec. I believe it could work without this annoying step, just by changing the filter class, but I did not try.

cx_Oracle and Apache revised

,

Don't know why, but I couldn't make apache find the correct path to Oracle lib so I had to use os.environ['ORACLE_HOME'] and os.environ['LD_LIBRARY_PATH'] with the same values of the previous post BEFORE the database settings (ok, it may not be necessary to be before, but it's better for your teammates).

In fact I even tried to use SetEnv in my httpd.conf just like we do for Django settings, but no luck, just after putting it on my settings that it finally worked.

cx_Oracle and Debian

,

Estava tendo vários problemas para instalar o cx_Oracle no Debian por causa de erros de build

no fim descobri que precisava do pacote python2.4-dev e desses comandos

#change for your oracle client path
export ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME:$ORACLE_HOME/lib


depois disso pude instalar o cx_Oracle pelo código fonte:

python setup.py build
python setup.py install


I was having many problems to build cx_Oracle and I had to install python2.4-dev package and export these variables

cx_Oracle and Debian

,

Estava tendo vários problemas para instalar o cx_Oracle no Debian por causa de erros de build

no fim descobri que precisava do pacote python2.4-dev e desses comandos

#change for your oracle client path
export ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME:$ORACLE_HOME/lib


depois disso pude instalar o cx_Oracle pelo código fonte:

python setup.py build
python setup.py install


I was having many problems to build cx_Oracle and I had to install python2.4-dev package and export these variables

cx_Oracle and Debian

,

Estava tendo vários problemas para instalar o cx_Oracle no Debian por causa de erros de build

no fim descobri que precisava do pacote python2.4-dev e desses comandos

#change for your oracle client path
export ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME:$ORACLE_HOME/lib


depois disso pude instalar o cx_Oracle pelo código fonte:

python setup.py build
python setup.py install


I was having many problems to build cx_Oracle and I had to install python2.4-dev package and export these variables

Instant Client and cx_Oracle on Windows Vista 64

I had some problems to intall cx_Oracle for using Oracle in Django but after some tough hours I finally got what happened.

cx_Oracle must use 32 bit dll, not the 64 bit version

Another problem I had was using the version 11.1.0.7 of Instant Client. It just didn't worked with XE so I had to use the 10.2.0.4 version and it was fine. You just have to unzip the content and put the directory in your Path environment variable.

I used the cx_Oracle 4.4 pre-compiled to python 2.5


if you are having problem to make cx_Oracle work, I think that with those tips you will help you to find the necessary files.

Here the necessary links:
http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html

http://sourceforge.net/project/downloading.php?groupname=cx-oracle&filename=cx_Oracle-4.4-10g.win32-py2.5.msi&use_mirror=ufpr

Today's fortune

,

"my happiness cannot be separated from yours"

Linda Galijan

Enso no Windows Vista 64

Agora que estou com um notebook novo era hora de instalar meus aplicativos básicos, entre eles o Enso.

Tirando os N bugs que encontrei, ao instalar o enso foi o pior que não tinha nenhuma pista do porquê ele não encontrava nenhum aplicativo.

Depois de usar uma ferramenta de desinstalação manual fornecida por eles, descobri que o diretório AppData (oculto) no meu diretório inicial C:\Users\anderson\AppData e todos os demais estavam somente como leitura, alterei a propriedade, desinstalei o Enso e instalei novamente e funcionou.

Apesar de que aparentemente nunca saía de Somente Leitura, funcionou e agora posso ter todas minhas aplicações rapidinho.

Atualização: Aparentemente este problema está relacionado ao Enso Beta Products e não ao launcher. Tente desinstalar e instalar somente o launcher.

Overview:
I was installing Enso on my Windows Vista 64 notebook and it wasn't showing applications on Open Command but the installation didn't report any error message.
I used a tool to manual uninstall and I found that there was a reading problem on my C:\Users\anderson\AppData directory. After make it writeble again (beside Windows set up it again) worked fine.
UPDATED: It seems that this problem is related to some Beta Producs. If you got this error, try to uninstall and install only the Launcher.

Castanha é bom e eu gosto

, ,

Apesar de ser vegetariano há quase 8 anos e sempre ter tido uma saúde boa, principalmente nos últimos meses sentia um cansaço e um estresse que era em partes devido à pressão do trabalho e em partes algo que eu não sabia direito.
Como sempre fui muito ansioso e queria petiscar sempre durante a tarde, resolvi fazer um "snack" de castanhas, com várias nozes, sementes, castanha-do-pará, avelã e frutas secas em um saquinho, para beliscar de quando em quando.

Resultado: Minha fome parou, pois algumas castanhas são o suficiente para saciar a vontade de comer algo entre as refeições, estou dormindo melhor e me sinto menos estressado e mais concentrado.

Curioso com o fato, fui procurar saber mais e achei dois artigos que me deixaram contente, agora sei que um saquinho de castanhas faz muito bem, principalmente para vegetarianos:

http://www.saudevidaonline.com.br/frutas.htm

Que diz:
NOZ - É bom remédio para o cérebro e para o sistema nervoso em geral.


E este

http://bemstar.globo.com/index.php?modulo=colunistas_mat&url_n_art=370&url_col=Dra.+Iara+Pasqua
Que diz:
A castanha do Pará nunca pode falta da dieta de um vegetariano, pois possui excelsina, uma proteína considerada completa. Mas, sua maior vantagem é a grande quantidade de selênio que possui. Nosso solo é pobre em selênio e este mineral é fundamental para o organismo, pois além de antioxidante, é um nutriente fundamental para o funcionamento cerebral.


Ou seja, veganos e vegetarianos do meu Brasil, é noz na fita (piada infame, eu sei, mas nunca disse q castanhas deixavam as pessoas inteligentes)



December 2009
M T W T F S S
November 2009January 2010
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31