domingo, 7 de agosto de 2011

Como instalar Pinax 0.9 e Django 1.2.3 com virtualenv no kinghost

Servidor Kinghost:
  • CentOS - Linux imia.kinghost.net Kernel 2.6.31
  • Python 2.4.3
  • Django 1.0.4 final
  • Apache/2.2.3 - Jan 15 2008 20:33:30
    • mod_WSGI DAEMON MODE

Preciso modificar o Django para versão 1.2.3 para instalar o Pinax 0.9a (última versão).

Instalando virtualenv:
 $ easy_install virtualenv  
Criando um ambiente de desenvolvimento no virtualenv:
 $ python /home/<seu-nome>/apps_wsgi/.site-packages/virtualenv <seu-ambient> 

Instalando PIL - Python Image Library
 $ easy_install PIL  

Instalando Pinax 0.9 (versão de desenvolvimento):
 $ pip install Pinax  

Entre no ambiente criado
 $ source <seu-ambient>/bin/activate  

Escolha um dos projetos Pinax
 $ pinax-admin setup_project -l  

Clone o projeto (clonando "social" no exemplo abaixo)
 $ pinax-admin setup_project -b social dev 

Para esse exemplo chamei meu projeto de "dev" e logo depois o renomei para "_dev":
 $ mv dev _dev 

Assim eu posso ir até o painel de controle e criar um projeto Django com o nome "dev" e após finalizado o processo de criação copiar o conteúdo da pasta "_dev" para "dev" aproveitando assim todas as configurações no servidor e do meu projeto Pinax.

Para finalizar é preciso modificar o arquivo dev.wsgi:
 import os, sys  
 activate_this = '/home/<seu-nome>/pinax/pinax-dev/bin/activate_this.py'  
 execfile(activate_this, dict(__file__=activate_this))  
 paths=['/home/<seu-nome>/apps_wsgi',  
     '/home/<seu-nome>/apps_wsgi/dev/apps']  
 for path in paths:  
   if path not in sys.path:  
     sys.path.append(path)  
 os.environ['PYTHON_EGG_CACHE'] = '/home/<seu-nome>/apps_wsgi/.python-eggs'  
 os.environ['DJANGO_SETTINGS_MODULE']='dev.settings'  
 from django.core.handlers.wsgi import WSGIHandler  
 application=WSGIHandler()  

Fontes:
Pinax - http://pinaxproject.com/docs/dev/gettingstarted/
Pinax Docs - http://pinaxproject.com/docs/dev/
VirtualEnv - http://www.arthurkoziel.com/2008/10/22/working-virtualenv/
WSGI - http://code.google.com/p/modwsgi/wiki/VirtualEnvironments

segunda-feira, 25 de julho de 2011

Django página de erro 403, customizar template

Hoje precisei alterar e customizar a página de erro 403 (acesso negado) do Django. Como não encontrei um tutorial simples para apenas modicar o template da página resolvi escrever o que fiz.

Descobri que existe um arquivo em ".../site-packages/django/views/csrf.py" que é responsável pela página de erro 403 no Django padrão.

Dai copiei o arquivo completo para a pasta do meu projeto. (.../meu-projeto/csrf.py)

Depois adicionei:

.../settings.py
 ...  
 CSRF_FAILURE_VIEW = 'csrf.csrf_failure'  
 ...   

Pronto!

Dentro do arquivo csrf.py há o html usado na mensagem de erro 403 assim você pode alterar esse html como preferir.

Pelos mesmos motivos que fizeram os desenvolvedores deixarem o html no arquivo csrf.py eu prefiro manter e alterar o html dentro do arquivo.

Mas você pode criar um arquivo 403.htlm na pasta de templates.

Logo adicione:
.../csrf.py
 ...  
 #from django.template import Context, Template  
 from django.template import Context, Template, loader  
 ...  
 def csrf_failure(request, reason=""):  
   ...  
   try:
      t = loader.get_template('403.html')
   except:
      t = Template(CSRF_FAILRE_TEMPLATE)# Se o template nao for encontrado
   ...  

Nesse exemplo o tratamento da exceção vai abrir arquivo 403.html não existir ocorrerá um erro e abrirá o CSRF_FAILRE_TEMPLATE contido acima no arquivo.

Divirta-se ^-^

fontes:
https://docs.djangoproject.com/en/1.3/ref/settings/#std:setting-CSRF_FAILURE_VIEW
http://mitchfournier.com/2010/07/12/show-a-custom-403-forbidden-error-page-in-django/

Easy Django em Português

Boa tarde,

após pensar um pouco decidi escrever minhas postagens em Português pois dessa forma pretendo ajudar aqueles que aqui no Brasil encontram dificuldades com a documentação em Inglês.

Good afternoon,

after think while I've decided to write my posts at Portuguese with the intention of help those that here in Brazil have difficulty to the English documentation.

quinta-feira, 9 de junho de 2011

Hello everybody!

Easy Django Installation Script was updated to Django version 1.2.5.
Enjoy ^-^

 $ git clone git@github.com:morenopc/Easy-Django-Scripts.git  
 $ cd Easy-Django-Scripts  
 $ chmod 755 easy_install_django.sh  
 $ ./easy_install_django.sh  

* The script will ask you to create a mySQL account and the root password after that the password will required to create the Django tables.

After you followed the instructions open http://127.0.0.1:8000/ and see the Django Hello World page.

This script is just a quick start please check http://www.djangoproject.com/ for tutorials and more information.

Moreno at Campus Party 2011

sábado, 19 de fevereiro de 2011

Django Better Form - on Server

System - Sistema: Server - Servidor
Python version unknown
Django version unknown

Installing and configuring django-form-utils on Server
Without easy_install command

Extras: Multi-edit
Ubuntu Gedit (very useful) plugin
Get Multi-edit!

Uninstalling previous django-form-utils easy_install installation:
 $ sudo easy_install -mxN django-form-utils  

Start a form-utils django app in your project:
 $ python manage.py startapp form_utils  
and then:
Download django-form-utils python source code
Download django-form-utils 0.2.0
or
django-form-utils project page
finally:
copy the content of file form_utils downloaded to your form_utils app.

Enjoy! Divirta-se!

domingo, 13 de fevereiro de 2011

Django Better Form

System - Sistema:
Ubuntu 10.04 LTS - the Lucid Lynx
Python 2.6.5
Django 1.2.4 final

Installing and configuring django-form-utils

 $ sudo apt-get install python-setuptools  
 $ sudo easy_install django-form-utils

Including form_utils:
.../settings.py
 
 INSTALLED_APPS = (  
   'django.contrib.auth',  
   'django.contrib.contenttypes',  
   'django.contrib.sessions',  
   'django.contrib.sites',  
   'django.contrib.messages',  
   'django.contrib.admin',  
   ...  
   'form_utils',  
 )  

Now change:
.../forms.py

 #from django import forms  
 from form_utils import forms  
 ...  


 class fooModelForm(forms.BetterModelForm):  
   class Meta:  
     model = fooModel  
     exclude = ('foo_field',)  
     fieldsets = [('Personal data', {'fields': ['name', 'email', 'phone'],  
                      #'description': 'Information',  
                      'classes': ['Personal data']  
                     }),]  
     row_attrs = {'name': {'class': 'style_names'},  
            'email': {'class': 'style_email'},  
            'phone': {'class': 'style_phone'},}  
and:
.../template/form.html
 <form action="." method="POST">{% csrf_token %}  
   {% if form.non_field_errors %}{{ form.non_field_errors }}{% endif %}  
   {% for fieldset in form.fieldsets %}  
     <fieldset class="{{ fieldset.classes }}">  
       {% if fieldset.legend %}  
         <legend>{{ fieldset.legend }}</legend>  
       {% endif %}  
       {% if fieldset.description %}  
         <p class="description">{{ fieldset.description }}</p>  
       {% endif %}  
       <ul>  
         {% for field in fieldset %}  
           {% if field.is_hidden %}  
             {{ field }}  
           {% else %}  
             <li{{ field.row_attrs }}>  
               {{ field.errors }}  
               {{ field.label_tag }}  
               {{ field }}  
             </li>     
           {% endif %}  
         {% endfor %}  
       </ul>  
     </fieldset>  
   {% endfor %}  
   <input type="submit" value="Enviar!" class="button">  
 </form>  

More information: https://bitbucket.org/carljm/django-form-utils/src/
Also: http://djangosnippets.org/snippets/1314/

sábado, 5 de fevereiro de 2011

Django on Mac OS X 10.6.6 cookbook

System - Sistema:
  • Mac OS X Version 10.6.6 - Snow Leopard
  • Python 2.6.1 - default
Extras:
Tiker Tool
To show the hidden mac files at finder and others functionalities

Install MySQL:
 $ curl -O http://mirror.services.wisc.edu/mysql/Downloads/MySQL-5.5/mysql-5.5.8-osx10.6-x86_64.dmg  
 $ sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /usr/local/mysql/support-files/mysql.server  

Locate the configuration defining the basedir and set the following :
basedir=/usr/local/mysql
datadir=/usr/local/mysql/data
Creating and configuring MySQL to Django:
 $ /usr/local/mysql/bin/mysql -u root  
 CREATE DATABASE django CHARACTER SET utf8 COLLATE utf8_general_ci;  
 GRANT ALL PRIVILEGES ON django.* TO 'django'@'localhost' IDENTIFIED BY '<password>';  


XCode:
Download and install XConde for GCC and others

MySQLdb:
provides the Python bindings to interface with the database.

 $ curl -O http://internap.dl.sourceforge.net/sourceforge/mysql-python/MySQL-python-1.2.3.tar.gz  
 $ tar -xvzf MySQL-python-1.2.3.tar.gz  
 $ cd MySQL-python-1.2.3  

Edit the site.cfg file:
Uncomment the line that begins #mysql_config =

Edit the path to point to /usr/local/mysql/bin/mysql_config:

mysql_config = /usr/local/mysql/bin/mysql_config
Complete the build and installation:
 $ python setup.py build  
 $ sudo python setup.py install  
 $ cd ..
  

IPython - optional
 $ curl -O http://ipython.scipy.org/dist/ipython-0.10.1.tar.gz  
 $ tar -xvzf ipython-0.10.1.tar.gz  
 $ cd ipython-0.10.1  
 $ python setup.py build  
 $ sudo python setup.py install  
 $ sudo python setup.py install_scripts --install-dir=/usr/local/bin  
 $ cd ..  

Install Django:
Exemplo where place django source code:

 $ cd ~  
 $ mkdir django  
 $ cd django  
 $ mkdir src  
 $ cd src  

Unpacking and installing:
 $ tar xzvf Django-1.2.4.tar.gz  
 $ cd Django-1.2.4  
 $ sudo python setup.py install  

Last MySQLdb fix:
 $ export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/  

Last Python Path fix:
 $ export PYTHONPATH=<pasta onde baixou o django>  
 Ex.:  
 $ export PYTHONPATH=/Users/dev/django/src