Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Mobile Django Admin Patches
In addition to adding a couple of minor, but useful (at least for me), patches to to the awesome django-mobileadmin project by Jannis Leidel, I learned something new about how Python works. The first patch was simply removing an extra slash from a URL in a template. No big deal: commit 599f172df85586742b5b1ef2bd5b7a24298a0839 Author: Patrick Altman <patrick@###.com> Date: Wed Dec 31 23:13:57 2008 -0600 fixed bug where app links had an extra trailing slash diff --git a/mobileadmin/templates/mobileadmin/mobile_safari/index.html b/mobileadmin/templates/mobileadmin/mobile_safar index 046a39d..1d66f59 100644 --- a/mobileadmin/templates/mobileadmin/mobile_safari/index.html +++ b/mobileadmin/templates/mobileadmin/mobile_safari/index.html @@ -10,7 +10,7 @@ {% if app_list %} <ul id="applist" selected="true"> {% for app in app_list %} - <li><a href="{{ app.app_url }}/" id="{{ app.name|slugify }}_app">{% blocktrans with app.name as name %}{{ name }}{% + <li><a href="{{ app.app_url }}" id="{{ app.name|slugify }}_app">{% blocktrans with app.name as name %}{{ name }}{% <script type="text/javascript">truncate({'{{ app.name|slugify }}_app': 35});</script> {% endfor %} </ul> The second patch took a bit more research to figure out what was going on. The symptom I was witnessing was that the mobile interface looked fine in my iPhone until I tried to view a model's list of objects. It kept showing me the default admin view (as you would expect to on the desktop) and it … -
Mobile Django Admin Patches
In addition to adding a couple of minor, but useful (at least for me), patches to to the awesome django-mobileadmin project by Jannis Leidel, I learned something new about how Python works. The first patch was simply removing an extra slash from a URL in a template. No big deal: commit 599f172df85586742b5b1ef2bd5b7a24298a0839 Author: Patrick Altman <patrick@###.com> Date: Wed Dec 31 23:13:57 2008 -0600 fixed bug where app links had an extra trailing slash diff --git a/mobileadmin/templates/mobileadmin/mobile_safari/index.html b/mobileadmin/templates/mobileadmin/mobile_safar index 046a39d..1d66f59 100644 --- a/mobileadmin/templates/mobileadmin/mobile_safari/index.html +++ b/mobileadmin/templates/mobileadmin/mobile_safari/index.html @@ -10,7 +10,7 @@ {% if app_list %} <ul id="applist" selected="true"> {% for app in app_list %} - <li><a href="{{ app.app_url }}/" id="{{ app.name|slugify }}_app">{% blocktrans with app.name as name %}{{ name }}{% + <li><a href="{{ app.app_url }}" id="{{ app.name|slugify }}_app">{% blocktrans with app.name as name %}{{ name }}{% <script type="text/javascript">truncate({'{{ app.name|slugify }}_app': 35});</script> {% endfor %} </ul> The second patch took a bit more research to figure out what was going on. The symptom I was witnessing was that the mobile interface looked fine in my iPhone until I tried to view a model's list of objects. It kept showing me the default admin view (as you would expect to on the desktop) and it … -
PimenTech Garage : On code aussi en Français
Note Le script "rest2site" écrit en shell a été abandonné. En effet, le souhait d'utiliser des tags, des commentaires, de contrôler le html m'a mécaniquement dirigé vers Django. English readers Technical documentations are now written in english (translations in progress..). Questions / Réponses C'est quoi ce site ? Des documentations en vrac, organisées par tags. Le site principal de PimenTech se trouve ici : http://www.pimentech.fr . Pourquoi "Garage" ? Parce que PimenTech Labs, c'est banal et prétentieux. Contexte d'utilisation Nous travaillons sur un grand nombre de projets et nous manquons toujours de temps pour communiquer et faire des documentations. Quand ça nous arrive, nous faisons du LaTeX pour le papier, du html pour notre site, et des mails pour des petites infos a partager. L'idée est de générer des documentations au format reStructuredText_ . Fonctionnement Tout ajout de fichier ".rst" dans l'arborescence CVS d'un module candidat [1] apparaîtra sur le site à chaque lancement de la fonction build_documents présent dans build_documentation.py. Note L'extension officielle pour les fichiers RestTructured Text est '.txt', mais je trouvais ça trop contraignant : on a déjà plein de .txt dans nos sources. [1]les modules qui seront présents dans jim:/home/fredz/src TODO Améliorer la recherche par tags … -
Using Django outside server
Site's module must be in PYTHONPATH. Script example : #!/usr/bin/env python import sys, os sys.path.insert(0, os.environ['HOME'] + "/lib/python") os.environ['DJANGO_SETTINGS_MODULE'] = "site_garage.settings" # Ca y est, on peut faire du Django from site_garage.build_documentation import * build_documents() ... Full Article -
deploiement
Déploiement d'une application Django Author:Frédéric de Zorzi Contact:fredz@_nospam_pimentech.net Revision:$Revision: 8419 $ Date:$Date: 2010-02-26 16:26:59 +0100 (Fri, 26 Feb 2010) $ Copyright:This document has been placed in the public domain. Tags:django system apache OUTDATED Il y a trois choses à dissocier dans un projet Django : Les applications La conf du site : le fichier setting.py Les templates propres au site Du point de vue Apache <Location "/"> # On utilise mod_python pour ce chemin : SetHandler python-program # Qui lui même utilise Django : PythonHandler django.core.handlers.modpython # Qui utilise les propriétés de "monsite" : SetEnv DJANGO_SETTINGS_MODULE monsite.settings </location> Emplacement des applications Les applications pouvant être utilisées par plusieurs sites ou par des scripts python, le meilleur emplacement pour elles est dans /usr/lib/pythonX.X/site-packages. Pour nous, le mieux est de les mettre dans django_pimentech. Pour l'installation, on utilise distutils : from distutils.core import setup from distutils.command.install_data import install_data from distutils.command.install import INSTALL_SCHEMES import os import sys class osx_install_data(install_data): # On MacOS, the platform-specific lib dir is /System/Library/Framework/Python/.../ # which is wrong. Python 2.5 supplied with MacOS 10.5 has an Apple-specific fix # for this in distutils.command.install_data#306. It fixes install_lib but not # install_data, which is why we roll our own install_data class. … -
Authentification Django dans MDM
L'authentification du nouvel intranet Century 21 a été complètement réécrite pour bénéficier des mécanismes avancés fournis par Django. Backends d'authentification Depuis le 28 juin 2006, la branche multi-auth de Django a été intégrée dans la branche principale. Cette branche ajoute la possibilité de définir des backends d'authentification supplémentaires, qui permettent de s'authentifier autrement que par la méthode standard (en utilisant User). En Django, un backend d'authentification est simplement une classe Python qui définit deux méthodes : une méthode authenticate() qui prend en paramètre un login et un mot de passe, et qui retourne un objet de la classe User Django. une méthode get_user(), qui à partir d'un user_id, retourne l'objet User en question. Ces backends sont déclarés dans settings.py de la manière suivante : AUTHENTICATION_BACKENDS = ( 'dj.auth.backends.C21Backend', 'django.contrib.auth.backends.ModelBackend', ) La variable AUTHENTICATION_BACKENDS est un tuple de chemins vers des backends. Ces backends sont « essayés » dans l'ordre, les un après les autres. Dès que l'on peut s'authentifier auprès de l'un d'eux, l'utilisateur est accepté. On a donc défini un backend supplémentaire, dj.auth.backends.C21Backend, qui authentifie l'utilisateur en utilisant Est_employe_par : from django.contrib.auth.models import User from dj.auth.models import C21UserProfile from dj.mdm.models import EstEmployePar class C21Backend: """ Authenticate against dj.mdm.models.EstEmployePar """ … -
PimenTech libcommonDjango API
Installation This package require python-docutils svn checkout http://svn.pimentech.org/pimentech/libcommonDjango cd libcommonDjango make install Trac access : http://trac.pimentech.org/pimentech/browser/libcommonDjango Django admin modules CSV and Stats modules We have started to add some modules to admin interface. The CSV module allow to import export data files per table, in admin fields order. It supports multiple encodings. New buttons on admin lists. CSV Import/Export form Add/Change stages The admin add/change stage function have been overloaded by pim change/add stage functions : if creation_auth_user and modification_auth_user fields are present in table, these fields are updated with logged user.id. Installation in settings.py, put 'django_pimentech.common' in INSTALLED_APPS list, before 'django.contrib.admin'. in urls.py, replace 'django.contrib.admin.urls' by 'django_pimentech.common.urls' Custom Fields ReStructured text field DateField See http://svn.pimentech.org/pimentech/libcommonDjango/django_pimentech/fields.py FrenchDateField This field allows you to display the date in the french format (dd/mm/yyyy). It also provides extra-options to purpose a calendar beside the field. In order to use the calendar, you have to include the following javascripts in your header (adapt the urls according to your own settings): index.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Django_calendar Demo</title> <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/admin_media/js/core.js"></script> <script type="text/javascript" src="/admin_media/js/admin/RelatedObjectLookups.js"></script> <script type="text/javascript" src="/admin_media/js/calendar.js"></script> <script type="text/javascript" src="/pimentech/js/django_calendar.js"></script> <!-- Here a style for the calendar--> <style type="text/css"> .calendarlink { … -
My Django Emacs
I describe here some modes I have activated to work with emacs : Simply put these lines in your .emacs. Most of these modes are part of Emacs Uniquify When you have several buffers with same file name, like views.py, it is really boring to switch between views.py<3>, views.py<4>. With Uniquify, buffer names could be prefixed with parent directory, like admin/views.py, forms/views.py. (require 'uniquify) (setq uniquify-buffer-name-style 'forward) Ido Mode There is many modes other modes like Ido. I found it very pleasant to load and switch buffers, in conjunction with Uniquify. (require 'ido) (ido-mode t) Emacs 23 Not released yes (perhaps 2009 ?), but I use emacs-snapshot on my debian, to have anti-aliased rendering. deb http://emacs.orebokech.com lenny main I have activated bold face for keywords and italics for comments (set-face-bold-p 'font-lock-keyword-face t) (set-face-italic-p 'font-lock-comment-face t) JavaScript I like Js2Mode, with syntax error highliting. Downlad it and append these lines in your .emacs (autoload 'js2-mode "js2" nil t) (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode)) Editing Templates See http://code.djangoproject.com/wiki/Emacs . I personnaly use Django Html Mode, derived from html-mode : auto-indentation, smart closing html and django tags. (autoload 'django-html-mode "django-html-mode") (add-to-list 'auto-mode-alist '("\\.[sx]?html?\\'" . django-html-mode)) Some functions These two functions are very useful … -
Crawlers Limiter Middleware
Status In production. Abstract This little middleware has been written to prevent system overload caused by aggressive crawlers on huge django websites. In conjunction with memcached cache, this system is really fast and could be extended for other purposes. Regular hosts like bots are configured in a white-list. Installation get PimenTech libcommonDjango : svn checkout http://svn.pimentech.org/pimentech/libcommonDjango install it with "make install" Activation and configuration In your settings.py : Activate memcached cache backend. Remember that each django hit is logged and other cache systems would be too costly. :: CACHE_BACKEND = 'memcached://127.0.0.1:11211/' the best is to put the middleware in first position of MIDDLEWARE_CLASSES MIDDLEWARE_CLASSES = ( 'django_pimentech.middleware.crawler_limiter.CrawlerLimiterMiddleware', 'django.middleware.common.CommonMiddleware', ...other middlewares... ) configure the folowing parameters : import re CRAWL_WHITE_LIST = re.compile("127\.0\.0\.1|192\.168\.1\.*|66\.249\.65\.*|66\.249\.66\.*|74\.6\.8\.*") CRAWL_CACHE_DURATION = 2 CRAWL_SITE_COUNT = 50 CRAWL_CACHE_BANNED_DURATION = 60 * 5 CRAWL_WHITE_LIST : these ips are not concerned with the crawler limiter (66.249.65.*, 66.249.66.* : Google ; 74.6.8.* : Yahoo) CRAWL_CACHE_DURATION : duration in seconds of cache per ip. For each django connection, the client ip is stored. If the client hits the site before the expiration, the ipcounter is incremented, with a new expiration of CRAWL_CACHE_DURATION. Otherwise the ip key expires from the cache with its counter. CRAWL_SITE_COUNT … -
full_client_session
Full client session Author:Frederic De Zorzi Contact:fredz@_nospam_pimentech.fr Revision:8259 Date:2009-05-29 Copyright:This document has been placed in the public domain. Tags:django Status In production. Important update A severe bug has been found, caused by spaces and comma characters in values (not handled by Safari). Please update the middleware and the JavaScript. Abstract With this middleware, Django session values are stored in client cookies, accessible (r/w) directly in JavaScript (except private variables). Extremely useful if one wants to use specific session variables on cached pages with JavaScript. Introduction Putting pages in cache for medium to high-traffic sites is essential, but one might have to display some internet-user specific informations on these cached pages. For example, we rewrote in Django the old php-based *Century21 France* internet site. This site delivers 1.000.000 dynamic pages per day, the database contains all the Information System with 100.000 active properties modified in real-time. We found a way to cache/uncache dynamically property detail, but we had to show the user's selection of properties on this page : With this middleware, each session variable is stored in a client cookie in json, crypted for private session variables, like "_auth_user_id". So for example with the following Python code : request.session["user"] = … -
Generating Django Models from a PGML File
Les outils de conversion du schéma de la base de données ont été adaptés pour permettre la génération d'un modèle Django à partir du fichier PGML. Le document ci-dessous décrit les spécificités du fichier PGML pour les modèles Django. Data Types Les types de données <attribute name="*name*" type="*type*" .../> PGML attribute type Equivalent Django field text TextField() int4 IntegerField() date DateField() timestamp DateTimeField() float8 FloatField(decimal_places=2, max_digits=5) boolean BooleanField() url URLField() email EmailField() image ImageField() slug SlugField() rst RestField() [1] file FileField() [1]RestField() is a custom Django field, defined in libcommonDjango. If a length attribute is specified, as in: <attribute name="*name*" type="*type*" length="n".../> PGML attribute type Equivalent Django field text CharField(maxlength=n) float8 FloatField(decimal_places=2, max_digits=n) Special Parameters Table Level Options admin : (default: true) if admin is set to "false", the Admin subclass is not generated. isbig : (default: true) if isbig is set to "false", raw_id_admin=True Attribute Level Options Real Life Example ... Full Article -
Django PimenTech Howto
Memcached Memcached est d'après nos tests 4 fois plus rapide que le cache 'file://'. Il n'est pourtant pas utilisable directement : il faut installer le client Python que l'on peut télécharger ici : ftp://ftp.tummy.com/pub/python-memcached/ . Il s'installe de façon standard avec : python setup.py install Pour le backend de cache, il est possible d'utiliser des noms d'hôte à la place de l'IP qu'indique la doc officielle : CACHE_BACKEND = 'memcached://localhost:11211' Newforms, real life example Template form, simple version: <form action="." method="post"> {{ form }} <input class="envoyer" type="submit" value="{% trans "Envoyer" %}"/><br /> </form> Template form, expanded: <form action="." method="post"> <label for="nom" class="required">{% trans "Nom" %}</label>{{ form.nom }}{{ form.errors.nom }}<br /> <label for="prenom" class="required">{% trans "Pr&eacute;nom" %}</label>{{ form.prenom }}{{ form.errors.prenom }}<br /> <label for="email" class="required">{% trans "e-mail" %}</label>{{ form.email }}{{ form.errors.email }}<br /> <label for="web">{% trans "Web" %}</label>{{ form.web }}{{ form.errors.web }}<br /> <label for="societe" class="required">{% trans "Soci&eacute;t&eacute;" %}</label>{{ form.societe }}{{ form.errors.societe }}<br /> <label for="fonction" class="required">{% trans "Fonction" %}</label> {{ form.type_fonction_id }}{{ form.errors.type_fonction_id }}<br /> <label for="telephone">{% trans "T&eacute;l&eacute;phone" %}</label>{{ form.tel }}{{ form.errors.tel }}<br /> <label for="addresse">{% trans "Adresse" %}</label>{{ form.rue }}{{ form.errors.rue }}<br /> <label for="codepostal">{% trans "Code Postal" %}</label>{{ form.cp }}{{ form.errors.cp }}<br /> <label for="ville">{% trans "Ville" … -
Module de calendrier en AJAX
Le but est d'écrire un module de calendrier capable de s'insérer dans des applications existantes (Zen, NotesGroup, etc.) Ce module prendra en entrée un ou plusieurs fichiers au format iCalendar, et affichera les évènements correspondants. Il devra être capable de se « rafraîchir » tout seul lors de l'ajout, de la suppression ou de la modification d'un évènement. Modules utiles Python Un module Python pour lire et écrire les fichiers iCalendar : http://codespeak.net/icalendar/ Avec ce module, on peut facilement récupérer les évènements d'un fichier iCal, les parcourir dans une liste Python, et lire ou modifier les propriétés des évènements. Le module permet aussi d'effectuer la transformation inverse, c'est-à-dire d'écrire un fichier iCal à partir de la structure Python. Le module calendar de la lib std Python (http://www.python.org/doc/2.3/lib/module-calendar.html) permet de construire facilement le calendrier d'un mois donné, organisé en semaines. JSON pour avoir accès à la structure de données Python en JS (avec simplejson ?) Django Un nouveau module CVS est mis en place : libcommonDjango. Il contient l'application pimentech.pcalendar qui contient les vues Django pour le calendrier. JavaScript TODO À Faire En vrac, des idées et des choses qui restent à faire : gestion des fichiers ical multiples affichés sur … -
Catching up Before the End
It's funny, I've had mountains of "free" time lately and somehow, none at all available to do the simplest of cumulative tasks. I've not replied to the nineteen emails sitting in my inbox, and keeping this site up to date has clearly not been a priority. However, in an effort to "clean house" so to speak before the New Year, I'll try to cover everything here. If you like to read everything, I suggest taking a moment to procure a beverage. Carolling: A Reunion Way back in October, I received a text message from my old friend Michelle containing a request to re-capture some of our better memories by going carolling this year, an annual tradition we once supported by hadn't attempted for nearly a decade. Excited at the thought of it, I agreed to play my role and she recruited Gary (another old friend) and a Soprano friend of theirs for the task. I did some digging of my own and managed to coax Merry out as well and with a group of five very out-of-practise choir folk, we set out on December 19th to bring some Christmas cheer to the suburbs. The whole thing didn't go off nearly … -
Outsourcing Revisited And No One Is Safe
The recent article Outsourcing Killed By Django And Ruby On Rails has caused as much proper debate as it has blind controversy. The feedback provided by readers here as well as other sites like Y Combinator and Reddit have brought up some good points. If I had to write the article again here [...] -
How I set up my development Mac
Starting a new job means setting up a new computer. With a clean slate, a blank canvas, a fresh start, if you will, I decided to document what I really need and use. MacBook Pro I haven’t used a desktop Mac since the late 90’s. My laptop goes everywhere with me. Of course, I have never, ever, used a Windows computer as my primary machine. Developer Tools The Apple developer tools come on a separate DVD and need to be installed. Don’t much care for XCode, but all the low level compilers are there. If you want to compile something from source, you’ll need them. Firefox Safari is nice, but for any type of real web development, you need Firefox, and a few extensions. Required extensions: Firebug: I can’t say enough about what this extension can do. Developing web sites would be so frustrating without it. My favorite features are the JavsScript console and CSS editing. Web Developer: My favorite usage of this addon is the ability to view the JavaScript-generated source code of a page. Typically Firefox will only show you the source of a page as it came from the server. Quartz PDF: One thing I miss about Safari is the ability to view … -
Web Statistics Shortcoming
I recently read about django-webalizer http://github.com/arneb/django-webalizer/tree/master I decided to set it up. I'd never really cared to analyze my log files before. I set up webalizer, and it was great. The django-webalizer app provides a good interface for my statistics. I'll definitely include it for any freelance work I might do in the future. When I ran webalizer on my site for the first time, I realized there were a couple broken links, and I noticed there were some things I could do to better my site. I don't use a favicon, so I had several hundred 404s in my log. I also analyzed logs for a public facing site at work, and fixed quite a few things. This was good, but all those errors that happened at the beginning of the month have been taken care of. webalizer doesn't have an option where I can generate a report from the last 24 hours. A report like that is useful because I can see what is happening with my websites now. I decided to look into other open source log analyzers. I haven't looked super hard, but it seems like awstats and webalizer are the two super active log analyzer … -
Users and the admin
So, for as long as I can remember the single most-frequently-asked question about the Django admin has been some variation of “how do I set a foreign key to User to automatically be filled in with request.user?” And for a while the answer was that you couldn’t do that, really; it was and still is easy to do with a custom form in your own view, but up until a few months back ... Read full entry -
Users and the admin
So, for as long as I can remember the single most-frequently-asked question about the Django admin has been some variation of “how do I set a foreign key to User to automatically be filled in with request.user?” And for a while the answer was that you couldn’t do that, really; it was and still is easy to do with a custom form in your own view, but up until a few months back ... Read full entry and comments -
Markdown w/ Pygments: Round 2
Dig back into my vast blog archive and you will find this post: I said it, I did it. Therein you will find my bumbling, ham-fisted solution for integrating pygment code highlighting into markdown. I just wandered back past this code today and then stumbled across the actual right way to do this. Quoth me: Pygments as [sic] a markdown pre-processor. Ideally one would be able to just pass this through as an extension to markdown using the functionality in the existing template tag. Unfortunately, pre-processors seem to be a different sort of animal. In the end I couldn't keep things very DRY. Well, I was half right. Introducing this extra functionality via an extension is the ideal solution. But pre-processors are only different from extensions in that they're just one of kinds of things you can enable via extensions. I've righted past wrongs. Here is the proof, in diff form: --- /dev/null+++ b/build/site/lib/mdx_pygments.py@@ -0,0 +1,9 @@+import markdown+from pg_md_processor import CodeBlockPreprocessor++class PygmentsExtension(markdown.Extension):+ def extendMarkdown(self, md, md_globals):+ md.textPreprocessors.insert(0, CodeBlockPreprocessor())++def makeExtension(configs=None):+ return PygmentsExtension(configs=configs)--- a/build/site/pocketuniverse/pygmented_markdown/templatetags/pygmented_markdown.py+++ /dev/null@@ -1,64 +0,0 @@-from django import template-from django.conf import settings-from django.utils.encoding import smart_str, force_unicode-from django.utils.safestring import mark_safe--from markdown import Markdown--from pg_md_processor import CodeBlockPreprocessor--register = template.Library()--@register.filter-def markdown(value, arg=''):- """- … -
Wszystkiego najlepszego wszystkim miłośnikom Django
Wesołych Świat Bożego Narodzenia, oraz szczęśliwego Nowego Roku 2009 życzy, zespół Taulab. Podzielcie się z nami opłatkiem wchodząc na stronę: http://podzieloplatek.pl/TAULAB/. Zostawcie po sobie życzenia ;). -
Django Site of the Week - Ooh-Ga-Boo-Ga
For the second Django SOTW, I had a chat to Bruce Kroeze about one of his Satchmo projects, Ooh-Ga-Boo-Gah. It's a great match of cool design and technical wizardry. For the un-initiated, Satchmo is one of Django's 'killer apps', providing an e-commerce platform that enables Django-powered shopping sites to be built with ease. Bruce is on the core development team and was able to provide us with a great insight into the project. You can read the interview now. Note: Due to Christmas and New Years, there will be no Django SOTW next week. We'll return on January 3rd, 2009. Have a great holiday season! -
Django Site of the Week - Ooh-Ga-Boo-Ga
For the second Django SOTW, I had a chat to Bruce Kroeze about one of his Satchmo projects, Ooh-Ga-Boo-Gah. It's a great match of cool design and technical wizardry. For the un-initiated, Satchmo is one of Django's 'killer apps', providing an e-commerce platform that enables Django-powered shopping sites to be … -
Announcing django-swingtime
Announcing django-swingtime -
Outsourcing Killed By Django And Ruby On Rails
The absolute pinnacle of outsourcing madness peaked with the publication of “The 4 Hour Workweek” by Timothy Ferriss. The book was a Bible for starting your own sweat shop. Everyone from one man startups long forgotten to mega corporations like Ebay were looking to India, China, and eastern Europe to cut development costs. [...]