Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
More django!
Ahh, finally... me and my co-worker convinced our boss to ditch our's lab www site based on Liferay. Among other problems, the big one was that there were three big unmaintanable catalogs each with separate Liferay instance.I don't want to criticize Liferay yet it's too big for our needs. It also does not fit in well into me and my co-worker skillsets (well it fit is a bit worse after I converted him from Java to Python ;).So we're looking for something that is: * possibly written in Python (easily extendable for us) * possibly Django compatibile (we have one service based on django and it would be nice if it could be easily put together, there'll be more django-based services in the future) I'm going to hunt something down on Monday. -
Django Site of the Week - Represent
Represent is a new website prototype from the New York Times that provides New York residents with information about the whereabouts of their elected representatives. What's interesting about this website is that it's one of the first large-scale sites to implement GeoDjango for spatially-aware applications. This week, I spoke with Derek Willis to get some details on their implementation of a Django project at one of the worlds' most famous newspapers. You can read the entire interview over at the Django site of the Week website. -
Django Site of the Week - Represent
Represent is a new website prototype from the New York Times that provides New York residents with information about the whereabouts of their elected representatives. What's interesting about this website is that it's one of the first large-scale sites to implement GeoDjango for spatially-aware applications. This week, I spoke with … -
Django Model Class Style Guide
Any constants and/or lists of choices The full list of fields The Meta class, if present The __unicode__() method The save() method, if it’s being overridden The get_absolute_url() method, if present Any additional custom methods Sources Practical Django Projects p. 62 (pre-1.0 old admin stuff omitted) Django Documentation -
Slicing A List Into Equal Groups in Python
There are several ways to do this, but I found out today that it’s possible to use itertools’ izip method to achieve the same effect as well, so I thought I would note it down here to reference later. Basically, we want to take a list and group it into sublists that don’t go over a specific length. I am using this to partition lists into rows, to be used as a Django template tag. Here is how it works with izip: >> from itertools import izip >> l = range(10) >> [s for s in izip(*[iter(l)] * n)] + [l[len(l) - (len(l) % n):]][[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] izip ignores the rest of the list if it doesn’t break cleanly, that’s why there has to be an additional part there to add the remainder of the items. Apparently a new method called izip_longest was introduced in 2.6 that takes extra items into account as well. It is also worth noting that some excellent partitioning filters can be found at Django snippets, this is mainly for fun! -
Using a metaclass for registering template tags
Writing your template tags requires too much boilerplate code. Period. I think we all agree on that. Let's see how we can improve it. A lot of times I find myself writing code like this (error handling omitted for clarity): @register.tag def my_menu(parser, token): tag_name, argument1, argument2 = token.split_contents() return MyMenuNode(argument1, argument2) class MyMenuNode(template.Node): def __init__(self, argument1, argument2): ... We are specifying the argument count and the template tag name twice, not exactly DRY friendly ;). After evaluating the solutions coming to my mind, I decided to go with a metaclass based approach, keeping the magic to a minimum. import inspect from django import template register = template.Library() class NodeType(type): def __init__(mcs, name, bases, dct): super(NodeType, mcs).__init__(name, bases, dct) if not mcs.is_node(name, dct): tag_name = ''.join(char if char.islower() else '_%s' % char.lower() for char in name)[1:-5] init = mcs.get_init(bases, dct) (args, varargs, varkw, defaults) = inspect.getargspec(init) arg_count = len(args) # not exactly arg count, but this way we avoid adding one in tag_function def tag_function(parser, token): arguments = token.split_contents() if len(arguments) != arg_count: raise template.TemplateSyntaxError('%s tag requires %d arguments' % (arguments[0], arg_count - 1)) return mcs(*arguments[1:]) register.tag(name=tag_name, compile_function=tag_function) def is_node(mcs, name, dct): return name == 'Node' and dct['__module__'] == __name__ … -
Keep your Django Applications in a Subfolder
To keep your Django applications neatly filed into a subfolder (such as apps/), first add the following to your settings.py: import os PROJECT_ROOT = os.path.dirname(__file__) Then in manage.py: Right under #!/usr/bin/env python add: import sys from os.path import abspath, dirname, join from site import addsitedir Right before if __name__ == "__main__": add: sys.path.insert(0, join(settings.PROJECT_ROOT, "apps")) [...] -
What is django.contrib?
Since it comes up a lot, I thought I’d spend a bit of time writing up my thoughts on what django.contrib really is, and what including a package in it really means. The following is just my personal opinion – really; that’s why this is posted here instead of over in the official Django documentation. However, most of the core team discussed this topic at length at DjangoCon, so I’m fairly sure there’s consensus over the rough outline. -
minibooks: Small Business Bookkeeping
Caktus released minibooks (open-sourced under the AGPL) as a bookkeeping package for small tech agencies. Boasting a double-entry accounting system, customer relationship management (CRM) and transaction reconciliation, minibooks provides a clean, multiuser web-based interface to manage simple accounting needs for small businesses. -
Using Django templates with jQuery AJAX
I recently discovered a neat way of displaying data retrieved using jQuery AJAX in concert with Django’s template engine. You can create a view in Django which simply uses the render_to_response shortcut function to render the results server-side and then just use jquery.load to dynamically fetch the results. Eventhough, returning some raw JSON data is […] -
Как работает SM.Org
Недавно расквитался в первом приближении с давно висящей и давящую на голову задачкой: опубликовал исходный код всех Джанго-приложений, которые поддерживают разные части SoftwareManiacs.Org. И меня посетила мысль поделиться тем, как оно вообще у меня тут все живет. Сайт SoftwareManiacs.Org работает на VPS-сервере (у компании TekTonic) и представляет собой сборную солянку ... -
Software Design Paralysis
Friends, I have come to an impasse. I have an awesome concept for embedding images into these blog posts. The idea is this: Use an Attachment model with a generic foreign key to allow images to be attached to blog posts Use a markdown extension to allow attached files to be referenced inside the blog post's body Here's the syntax I wanted to support in markdown: This isn't that impossible a task, and in fact, I have done it, but there are some wrinkles. The main issue is that I really want to limit my markdown extension's file lookup to only those files actually attached to the blog post. The second issue is that I would like to be able to specify a template to use for rendering each attachment, and I'd like to be able to specify different templates in different contexts. Both problems revolve around how I should do the actual conversion from markdown syntax to HTML. I implemented my solution as a markdown extension because I wanted to continue to use the markdown template filter. I'm already using it with the pygments extension I discussed earlier: {{ blogpost.body|markdown:"pygments" }} I was imagining that I could implement my … -
Django Site of the Week - EveryBlock
The Django Site of the Week is back after a Christmas-induced break with an interview with Adrian Holovaty. Adrian is no stranger to Django, and his name is known throughout the community as one of the brains behind Django's birth and subsequent open-source release. His latest project EveryBlock is the … -
Django Site of the Week - EveryBlock
The Django Site of the Week is back after a Christmas-induced break with an interview with Adrian Holovaty. Adrian is no stranger to Django, and his name is known throughout the community as one of the brains behind Django's birth and subsequent open-source release. His latest project EveryBlock is the evolution of an earlier mashup, chicagocrime.org, which won Adrian a number of awards. So what are the driving forces behind EveryBlock? I recently spoke with Adrian to find out. You can read the interview now over at Django Site of the Week. -
Django template tags – Google chart – python 2.4 port
I just tried the django template tags for the google charting api by Jacob. Unfortunately they were python 2.5 only and I happen to still be stuck to 2.4. The changes to move it to 2.4 were minimal though. Still to save some of you googlers out there the hassle: charts I was just browsing the code [...] -
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 … -
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 -
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 -
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 … -
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 … -
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 { … -
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" … -
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. …