Code for Begginners

lunes, 6 de octubre de 2008

Django: Build my first Model

We will need this reference, where you could find all possible kind of fields we could use to create our models.

All models in django extends from models.Model:

from django.db import models

We will start defining a class model as:

Class New(models.Model):

What we need to do next? define all fields.
By default django models provide a default key if you don't define one explicitly.

Before start defining our fields, our application needs to use internationalization so we will use:
from django.utils.translation import ugettext_lazy as _

this means that we will use _('text to translate') for every text we want to have a translation, so we will use it for the labels of our fields.

title = models.CharField(_('title'), max_length=45)

The CharField needs to have a max_length defined it.

date_published = models.DateTimeField(_('date published'))
content= models.TextField(_('content'))
mp3file = models.FileField(upload_to="mettings/low/", blank=True, null=True, help_text=_("This should be a low quality version (preferably 18kbps)"))
largemp3file = models.FileField(upload_to="mettings/high/",blank=True, null=True, help_text=_("Optional. Preferably a 64kps version."))

By default all fields are required, if you want to change this we will use blank=True and null=True.

Now we have our first model. Now we have to sync with the database:

./manage.py syncdb

*Before you do syncdb you have to add your application to the settings.py.

There is a funtion that it is important to define inside our model:

def __unicode__(self):
return self.title

and also the inner class Meta:

class Meta:
ordering = ('date_published',)
verbose_name = _('metting')
verbose_name_plural = _('mettings')

Verbose names are used as a labels for our News objects on our admin interface.
Ordering is the default order used in all our queries.

There is another usefull method called get_abosulte_url, this method return the url for each object in our model, it is used in addition to generic views, so we will discuss about this method in later.

There is also the alternative to override the save method, for example if you have to fields like:

created = models.DateField(default=datetime.datetime.now)
last_updated=models.DateField(default=datetime.datetime.now)

the date created it is saved once time, however date updated needs to be updated every time the user make a change in our model. Both of this fields are not managed by the user, the systems do all the work, so we nned to override the default save method as:

def save(self):
if self.pk:
self.last_updated = datetime.now()

if not self.created:
self.created = datetime.now()

super(MyModel, self).save()

miércoles, 17 de septiembre de 2008

Accediendo a los repositorios de github con git

Si eres usuario de github aca los pasos basicos para poder acceder al repositorio usando git.

1. Crear tus claves: #/ ssh-keygen -t rsa luego ingresa tu frase dos veces, cuidado con no recordarla despues :)
2. En tu carpeta de usuario copiar #cat .ssh/id_rsa.pub a tu cuenta en github, en la seccion donde te pide tu llave publica.
3. Obtener los files de tu repositorio: #git clone git@github.com:blah/blah.git


Ahora haces tus cambios, por cada file que cambies o directorio realizaz un #git add [file o directorio] y al final realizas un #git commit // te aparecera el vim, pones i para insertar tu comentario e inmediatamente despues pones :x para guardar y finalizar el commit. Para ver el estado puedes usar #git status, el cual te mostrara informacion de los cambios que estan ene el commit y los que dejaste fuera :)

Ahora subimos los cambios con: #git push

*Si el ultimo usuario en hacer commit y push no fuiste tu, entonces deberas hacer un #git pull antes de poder hacer el push y/o commit de tu codigo.

lunes, 1 de septiembre de 2008

ubiquity una consola en tu browser q acelera tu trabajo

Ubiquity es la ultima gran sorpres que lanzo mozilla, despues de tracemonkey realmente la web en muy poco tiempo tendra nuevas sorpresas y estaremos cambiando a un nuevo mundo.

Pero veamos ubiquity,

es un plugin que te permite realizar muchisimas tareas tan solo utilizando una linea de comandos embedida en tu browser obviamente firefox,

Primero installatelo desde la siguiente pagina https://people.mozilla.com/~avarma/ubiquity-0.1.xpi

Una vez instalado el plugin presiona ctrl+space para tener acceso a window de ubiquity.

Ahora probemos algunos comandos basicos:

Mandemos un email de prueba a dani: (ubiquity console# sera nuestra abreviacion para referirnos a la console de ubiquity)

ubiquity console# email to dani

Luego presionas enter y ya esta, utiliza el nombre de un amigo tuyo en vez de dani.

Ahora vamos a cualquier pagina, selecciona text e imagenes de esa pagina y presiona Ctrl + Space (llamada al console de ubiquity)

ubiquity console# email this to dani

Presionas enter, y veras como todo lo que seleccionaste aparecera en un nuevo email listo para ser enviado a dani.

Twitter

Soy muy fanatico de twiter asi que ete comando lo use ya como 10 veces antes de escribir este post.

ubiquity console# twitter esto lo mande desde ubiquity!!

Presionas enter, te pedira tu login y contraseña e inmediatamente en la parte inferior de tu browser veras un anuncio de mozilla indicandote que tu update fue entregado y publicado.

Google Maps

ubiquity console# map alexandria VA 22911

Te saldra una serie de listas de mapas, selecciona cualquiera y hazle click, veras el mapa en un tamaño mucho mas grande, si la pagina es editable podras insertar el mapa en ese lugar.

Translate

ubiquity console# translate hello world to spanish
Existem muchisimos comandos, velos en chrome://ubiquity/content/cmdlist.html.

lunes, 25 de agosto de 2008

DJango under Ubuntu 8.04

DJango is one of the most popular frameworks, now i will start setting up my ubuntu 8.04 for DJango.

Download and Install

#sudo apt-get install python2.5.2
#wget http://www.djangoproject.com/download/0.96.2/tarball/
#tar xzvf Django-0.96.2.tar.gz
#cd Django-0.96.2
#python setup.py install

Creating your first App called Wika

#sudo mkdir /var/www/django
#cd /var/www/django
#python /usr/lib/python2.5/site-packages/django/bin/django-admin.py startproject Wika

Run Server

#cd wika
#python manage.py runserver

Now open a browser with the specification displayed

So now we have created our App, so in the next chapter we will start with some basics to add new functionality to our application.

Image Transitioner under Prototype and Scriptaculous

This is a simple class but it could also write as a pair of two functions but i think it is better to organize your code and this is an alternative but also to make code for reuse, ok but this is not the point, this is a class that receives as a parameters the id for the containers, probably if you use a css class, you could use containers=$(class_parameter) instead of use an array, but you should use $A($(class_parameter)) to have access to array functionalities, so i wrote this little code and i will explain just the lines that maybe a java, c# wont notice.

var ImageTransitioner = Class.create(); //Define our ImageTransitioner class :)
ImageTransitioner.prototype = { //using .prototype we are able to add members to our prototype object(class in java)

initialize:function(containers, delayTime){ // initialize as in java is the constructor

this.id_containers=containers; this.actual=0;
this.interval = setInterval(this.imageTransition.bind(this),delayTime);

//bind it is used to maintain the context, to our object context, so we will able to use this.whatever

},imageTransition:function(){
Effect.Fade(this.id_containers[this.actual], { duration:2, from:1.0, to:0.0 });
this.actual++;
if (this.actual >= this.id_containers.lenght) this.actual = 0;
Effect.Appear(this.id_containers[this.actual], { duration:2, from:0.0, to:1.0 });
}
};

//The combination effects Fade and appear gives you a simple but pretty effect when you use for a collection of images that changes in some sections.

var imageEffect = new ImageTransitioner(new Array('box-1', 'box-2', 'box-3', 'box-4'),8000);

And the Html looks like:

1







What i don't like, is that we use the inline style: 'display:none' so if you have any comments or questions, please let me know.

Lets take a look the winners, if you want to skip the slides i listed below some categories:

Best of open source developer tools

Best of open source platforms and middleware

Best Opensource for Collaboration

Other winners:

domingo, 27 de julio de 2008

Prototype using PeriodicalExecuter

This function let us to execute some task periodically, it takes two arguments, the function
wich will be executed and the interval in secconds between executions.

For example i will use it to display two images in a alternate manner, you could see the demo at here.

This is a simple example and we will improve it in the nexts posts.


var i = 0;

function changeImage() {
 if(i%2==0){
  new Effect.Fade('image1', { // the id of the element containing the image
  duration: 1,
  fps: 50,
  afterFinish: function() { new Effect.Appear('image2', {duration: 1, fps: 50, queue:'end'})}
  });
 }else{
  new Effect.Fade('image2', { // the id of the element containing the image  duration: 1,
  fps: 50,
  afterFinish: function() { new Effect.Appear('image1', {duration: 1, fps: 50, queue:'end'})}
  });
 }
 i++;
}
window.onload = new PeriodicalExecuter(changeImage, 10);

Etiquetas

Powered By Blogger