06 Feb 2012

feedDjango community aggregator: Community blog posts

Apple lion reinstall experience and surprise

06 Feb 2012 2:12am GMT

05 Feb 2012

feedDjango community aggregator: Community blog posts

Configuring application settings for a Django project

I am currently working on a new project where I need application specific settings that a non-Django admin user can edit without editing a file. In this particular case, there is a "schedule" app, and I wanted to give a user the ability to add / remove timezones for that particular schedule. Besides that the setting application had meet the following requirements:

work with MongoDB or make it easy to create a backend to store settings
be...

05 Feb 2012 5:32pm GMT

03 Feb 2012

feedDjango community aggregator: Community blog posts

Release 0.6.5

We just released LFS 0.6.5. This is a yet another bugfix release.

Changes

  • Bugfix: added csrftoken for rating mails (Maciej Wi?niowski)
  • Bugfix: fixed ImageWithThumbsField (Maciej Wi?niowski)
  • Updated romanian translations (olimpiu)
  • Updated polish translations (Maciej Wi?niowski)

News:

Information

You can find more information and help on following locations:

03 Feb 2012 11:50pm GMT

02 Feb 2012

feedDjango community aggregator: Community blog posts

HTTP Status Codes Site

During the development of Simple Site Checker I realised that it would be useful for test purposes if there is a website returning all possible HTTP status codes. Thanks to Google App Engine and webapp2 framework building such website was a piece of cake. The site can be found at http://httpstatuscodes.appspot.com. The home page provides [...]

02 Feb 2012 4:36am GMT

Facebook open graph publishing simplified

Facebook has just enabled the open graph for 60 lucky apps. The new open graph beta allows you to post a user's actions to their timeline. This activity is shown to the user's friends in Facebook's newsfeed and ticker. Furthermore your data is nicely aggregated on a user's Facebook profile. Fashiolista's aggregation for instance looks [...]

02 Feb 2012 1:00am GMT

01 Feb 2012

feedDjango community aggregator: Community blog posts

django-cms 2.0.2 and Django 1.2 – 1.3

If you are running an old version of django-cms, you can still upgrade Django. I would strongly suggest doing this since it's very uncomplicated. However, if you are running django-cms 2.0, you should first upgrade to 2.0.2 and run the … Continue reading

01 Feb 2012 8:56pm GMT

Forms Part 4: Formsets

Formsets make life easier when it comes to dealing with multiple forms of the same type on the same page. In this episode we will show you how to set them up, and the basics of how to save that data to the database. It is not much different from dealing with single forms.
Watch Now...

01 Feb 2012 3:00am GMT

31 Jan 2012

feedDjango community aggregator: Community blog posts

Dajaxproject, primera part

Una de les preguntes més recurrents en les llistes de Django, junt amb la de quin editor fer servir és la de com fer cridades AJAX i quina llibreria utilitzar.

Django és agnòstic en el que fa a les llibreries javascript, tot i això la part de l'admin fa servir jQuery, però oficialment no hi ha cap llibreria especialment recomanada, Django és pot utilitzar amb qualsevol llibreria i dependrà del projecte que en triem una o altra.

El problema de que no es faci cap recomanació de com integrar cridades AJAX amb Django ens dóna molta llibertat, però també te l'emperò de que no hi ha cap guia de bones pràctiques sobre com fer-ho, des d'on posar la llibreria, quin nom li hem de donar, si la posam al views.py o no.

El la comunitat de codi obert quan hi ha un buid així i una necessitat ben aviat sorgeixen projectes que intenten donar una resposta. Un d'aquests projectes és el que us present en aquest article el dajaxproject.

Djaxaproject són de fet dues llibreries, dajaxice i dajax, la primera podríem dir que respon a la necessitat que us comentava de fer més senzilla la comunicació asíncrona entre les aplicacions Django y el codi javascript, la segona, dajax està molt més orientada cap a la capa de presentació i sobretot està lligada a un bastiment de javascript en concret, encara que tenim certa llibertat a l'hora de triar-lo.

En aquest apunt veurem primer Dajaxice i en un següent apunt faré també cinc cèntims de dajax.

Instal·lació

Suposaré com tantes vegades que teniu un virtualenv creat i Django instal·lat. També hem de partir d'un projecte base.

El primer que hem de fer és instal·lar la llibreria, per això bastarà fer un

pip install django-dajaxice

La documentació explica força bé el procés, així que resumeixo:

  1. Posar dajaxice dins la secció INSTALLED_APPS de settings.py
  2. Assegurar-nos que tenim eggs.Loader descomentat als TEMPLATE_LOADERS
  3. Assegurar-nos que django.core.context_processors.request és dins el TEMPLATE_CONTEXT_PROCESSORS, si no ho heu fet ja, el meu consell és que copieu tot el TEMPLATE_CONTEXT_PROCESSORS que hi ha a la documentació, ja que a poc que l'aplicació cresqui segur que necessitareu afegir-ne algun.
  4. Afegim als settings.py el prefixe que farem servir per distingir les urls de dajaxice de les de urls normals de la nostra aplicació, per exemple la documentació ens diu posar DAJAXICE_MEDIA_PREFIX="dajaxice".

Amb això ja hem fet par de la fontaneria, ara ve la part més interessant i la màgia d'aquesta aplicació.

Organitzant l'AJAX

Dajaxice el farà és utilitzar el prefixe que hem configurat per tractar certes urls com a cridades AJAX. Djaxice el que ens permet és registrar automàticament les funcions que es publicaran com a cridades AJAX utilitzant un mecanisme semblant al que fa dervir Django per a l'admin.

D'aquesta manera, una vegada modificat l'arxiu urls.py podem anar creant les funcions a publicar dins un arxiu ajax.py i registrar les funcions. Així l'arxiu urls.py ens ha de quedar com:

#!/usr/bin/python

from django.conf.urls.defaults import patterns, include, url
from dajaxice.core import dajaxice_autodiscover
from django.contrib import admin
from django.conf import settings

admin.autodiscover()
dajaxice_autodiscover()

urlpatterns = patterns('',
     url(r'^admin/', include(admin.site.urls)),
    (r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, 
        include('dajaxice.urls')),
)

Utilitzant AJAX a les nostres plantilles

Dajaxice es capaç de posar dins la nostra plantilla el codi que necessitam per fer les cridades AJAX i publicar les funcions que farem servir a partir del codi Python (ja ho veurem un poc més endavant). Per fer-ho fa servir una llibreria que s'ha de carregar.

Així a la part de càrrega de llibreries de la nostra plantilla haurem d'afegir: dajaxice_templatetags. Si encara no heu carregat cap llibreria doncs quedaria com {% load dajaxice_templatetags %}.

Una vegada carregada la llibreria posarem el tag que genera el codi javascript {% dajaxice_js_import %}. Ho podeu posar a la capçalera o al peu de la plana. Personalment, com que ho sol fer servir junt amb jQuery, ho pos al peu, abans de l'utilització de les llibreries, per tal de millorar la velocitat de càrrega de les planes.

Aquest codi es gener dinàmicament mentre estam desenvolupant. Us avís que de tant en tant es queda carregat en memòria i certs canvis requereixen reiniciar el servidor de desenvolupament. Si veis que heu publicat una funció i no surt, reiniciau el servidor.

En producció la llibreria té una opció per generar directament l'arxiu javascript i poder tractar-lo com un fitxer estàtic més.

L'estructura d'una plantilla bàsica amb djaxice seria doncs

{% load dajaxice_templatetags %}

<html>
  <head>
    <title>My base template</title>
    <!-- també al peu depen de l'aplicació -->
    {% dajaxice_js_import %} 
  </head>
...
</html>

Creant la nostra primera cridada AJAX

Com us comentava més amunt, una de la gràcia de dajaxice és que ens permet organitzar les nostres cridades AJAX. Així el que farem serà crear un arxiu ajax.py dins la nostra aplicació, de manera que podem agrupar cridades per aplicació.

Suposem que hem creat una aplicació anomenada main, la posam al settings.py del projecte i cream l'arxiu ajax.py

Crear una funció i publicar-la per a que la servim via AJAX és tan senzill com això:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from django.utils import simplejson
from dajaxice.decorators import dajaxice_register

@dajaxice_register
def hello_world(request):
    return simplejson.dumps(
        {'message':'Hello World'})

És a dir, importam simplejson per a fer la transformació cap a json, que és el que volem servir (o xml, o html, tant fa), cream una funció com ho feim al views.py de Django i la decoram amb
dajaxice_register. Això junt el autodiscover que hem posat a urls.py fa que ara la nostra aplicació pugui respondre a cridades AJAX.

Cridant des de l'html

Per cridar a la nostra funció es pot fer directament amb l'event onclick directament a l'HTML,però a mi particularment em fa molta grima tenir aquesta mescladissa, així que prefereixo tirar de jQuery encara que per fer la crida AJAX no el faci servir. Recordem que l'important no és el mètode amb que es fa la crida, sinó l'organització i facilitat de mantenimient (i depuració) que ens dóna la llibreria.

Així, en el meu cas quedaria:

<script src="https://ajax.googleapis.com/
    ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
    $(function(){
        $('#testme').click(function(event){
            event.preventDefault();
            Dajaxice.main.hello_world(test_callback);
        });

        function test_callback(data){
            if (data==Dajaxice.EXCEPTION){
                alert('Opps, alguna cosa dolenta ha passat');
            } else {
                alert(data);
            }
        }
    });
</script>

on #testme fa referència a un enllaç al qual hem assignat l'event.

L'interesant d'això és que tenim a la nostra disposició una funció javascript que mapeja la que tenim al codi Python i a la qual podem cridar amb uns paràmetres. El primer d'ells és la funció de tornada (el callback) que utilitzarem per gestionar la resposta i l'altra és un paràmtre codificat com json que passarà com a paràmetre cap a la funció.

Hem de dir que dajaxice sempre fa un POST contra la url, gestionant els problemes de CSRF.

Si posam DAJAXICE_DEBUG=True al settings.py o millor dit, ve així per defecte, a la consola de desenvolupament de Django podem veure tant la cridada que fem com la resposta i els errors que hi pugui haver.

La funció de tornada es defineix amb un paràmetre que contindrà el valor de retorn de la nostra cridada AJAX. Si és un json podrem accedir als valors directament, però com he comentat abans, no estam limitats a tornar json, podem tornar una cadena de text, xml, html, ... el que necessitem i poguem tractar amb javascript.

És interessant veure com es tracten els errors o les excepcions. Si hi ha problems al nostre codi Python i es llança una excepció, dajaxice la capturarà i llavors data contindrà el valor Dajaxice.EXCEPTION, amb la qual cosa sabem que quelcom ha anat malament.

He de fer servir sempre Dajaxice?

Depèn, algunes vegades serà més convenient fer una cridada directa amb jQuery, per exemple quan volem tenir més control del que passa quan s'inicia la cridada, o volem poder-la cancel·lar.

El cert, però, és que dajaxice ens permet organitzar millor el codi i gestionar d'una manera sistemàtica les nostres cridades AJAX. Com sempre no hi ha cap veritat absoluta, potser servirà en el 80% dels casos i això ja significa una gran ajuda.


0 comentaris, 0 trackbacks (URL)


Automatic translations of this post by Apertium

31 Jan 2012 4:38am GMT

Simple Site Checker

… a command line tool to monitor your sitemap links I was thinking to make such tool for a while and fortunately I found some time so here it is. Simple Site Checker is a command line tool that allows you to run a check over the links in you XML sitemap. How it works: [...]

31 Jan 2012 4:03am GMT

30 Jan 2012

feedDjango community aggregator: Community blog posts

Quick Django Class Based View Decorator

A quick way to use decorators on Django class based views using Python metaclasses.

30 Jan 2012 9:44pm GMT

Faking attributes in Python classes…

… or how to imitate dynamic properties in a class object Preface: When you have connections between your application and other systems frequently the data is not in the most useful form for your needs. If you have an API it is awesome but sometimes it just does not act the way you want and [...]

30 Jan 2012 2:00pm GMT

5 open-source Python/Django apps we love

The Python/Django duet is fantastic, everyone knows that. However it can be even more awesome with these apps: 1. South This is an intelligent schema and data migration tool. If you don't use it yet, you will want to after … Continue reading

30 Jan 2012 7:40am GMT

29 Jan 2012

feedDjango community aggregator: Community blog posts

Running sentry on DotCloud

Sentry is a realtime event logging and aggregation platform. At it's core it specializes in monitoring errors and extracting all the information needed to do a proper post-mortum without any of the hassle of the standard user feedback loop.

The main feature of sentry and the ability to send all of your application logs to on place, and then aggregate them, so that you only get one error email for the same error. This will keep your mailbox from flooding, when something goes wrong.

Putting your logging server on a different server or network then your production servers is a good idea, so that if something goes wrong, and you can't access your servers. You can still see what errors were getting thrown before the servers started having problems.

Follow these easy steps to get sentry up and running on DotCloud.

  1. Create a place to store your project
$ mkdir -p ~/projects
  1. Go into the projects directory
$ cd ~/projects
  1. Clone git repo from github, requires git client
$ git clone git://github.com/kencochrane/sentry-on-dotcloud.git
  1. Go into the new project directory
$ cd sentry-on-dotcloud
  1. Creating the virtualenv (using virtualenvwrapper, virtualenv, and pip)
$ mkvirtualenv --no-site-packages --distribute sentry-on-dotcloud
  1. Installing the dotCloud client http://docs.dotcloud.com/firststeps/install/ (here are the steps for Linux and Mac OSX)
$ sudo pip install -U dotcloud
  1. Sign up for a dotcloud account https://www.dotcloud.com/accounts/register/ if you haven't already.
  2. The first time you use the dotCloud account you will need to add your api key. So type dotcloud and follow the steps. You can find your API key at http://www.dotcloud.com/account/settings
$ dotcloud
  1. Create your dotcloud application
$ dotcloud create sentry
  1. Change the SENTRY_KEY settings in these files, to the same unique value.
    • sentry_conf.py
    • sentryproj/settings.py
  2. Add your email address to SENTRY_ADMINS in sentryproj/settings.py . This will send you emails when an error occurs.
  3. Push your code into dotcloud
$ dotcloud push sentry .
  1. Find out your application url
$ dotcloud url sentry
  1. Open url in your browser and start using sentry on dotcloud.
  2. First things first you should change the admin password from the default one that was created on deployment.
  3. Test out sentry using the raven client to make sure it is working as it should. Open up a python shell on your local machine and do the following.

Replace the server_url with your sentry url you found out in step 13. Make sure it ends in /store/ . Also make sure you replace my_key with your sentry key

>>> from raven import Client
>>> server_url = "http://sentry-username.dotcloud.com/store/"
>>> my_key='1234-CHANGEME-WITH-YOUR-OWN-KEY-567890'
>>> client = Client(servers=[server_url], key=my_key)
>>> client.create_from_text('My event just happened!')
('48ba88039e0f425399118f82173682dd', '3313fc5636650cccaee55dfc2f2ee7dd')

If you go to the sentry webpage you should see your test message. If not, double check everything, and see if there was any errors during the send.

Once this is all up and running you can install the raven client in your applications, and start sending your logs to sentry.

  1. Optional: If you don't like the URL they gave you, you can use your custom domain. Assuming your application was sentry.www and your domain was www.example.com you would do the following
$ dotcloud alias add sentry.www www.example.com

Once you get comfortable with how things work, don't forget to change your DEBUG setting to False. Go ahead and fork my project and get started today.

For more info about dotcloud, sentry, and Raven and what you can do with with it. Check out their docs
Links:

29 Jan 2012 10:12am GMT

26 Jan 2012

feedDjango community aggregator: Community blog posts

django CMS 2.2 roadmap update

django CMS 2.2 roadmap update

26 Jan 2012 12:27am GMT

django CMS 2.2 release candidate available

django CMS 2.2 release candidate available

26 Jan 2012 12:27am GMT

django CMS 2.1.2 released

django CMS 2.1.2 released

26 Jan 2012 12:27am GMT