Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Connecting anything to anything with Django
Edit 7/11/2011 I've added documentation and an example app. Introduction I'm writing this post to introduce a new project I've released, django-generic-m2m, which as its name would indicate is a generic ManyToMany implementation for django models. The goal of this project was to provide a uniform API for both creating and querying generically-related content in a flexible manner. One use-case for this project would be creating semantic "tags" between diverse objects in the database. Connecting Models What its all about is connecting models together and, if you want, creating some metadata about the meaning of that relationship (i.e. a tag). To this end, django-generic-m2m does three things to make this behavior easier: wraps up all querying and connecting logic in a single attribute that acts on both model instances and the model class allows any model to be used as the intermediary "through" model provides an optimized lookup when GenericForeignKeys are used An example Referring back to the diagram, let's create some models (these are the same models used in the testcases): from django.db import models from genericm2m.models import RelatedObjectsDescriptor class Food(models.Model): name = models.CharField(max_length=255) related = RelatedObjectsDescriptor() def __unicode__(self): return self.name class Beverage(models.Model): # ... same as above class … -
Connecting anything to anything with Django
Edit 7/11/2011 I've added documentation and an example app. Introduction I'm writing this post to introduce a new project I've released, django-generic-m2m, which as its name would indicate is a generic ManyToMany implementation for django models. The goal of this project was to provide a uniform API for both creating and querying generically-related content in a flexible manner. One use-case for this project would be creating semantic "tags" between diverse objects in the database. Connecting Models What its all about is connecting models together and, if you want, creating some metadata about the meaning of that relationship (i.e. a tag). To this end, django-generic-m2m does three things to make this behavior easier: wraps up all querying and connecting logic in a single attribute that acts on both model instances and the model class allows any model to be used as the intermediary "through" model provides an optimized lookup when GenericForeignKeys are used An example Referring back to the diagram, let's create some models (these are the same models used in the testcases): from django.db import models from genericm2m.models import RelatedObjectsDescriptor class Food(models.Model): name = models.CharField(max_length=255) related = RelatedObjectsDescriptor() def __unicode__(self): return self.name class Beverage(models.Model): # ... same as above class … -
Connecting anything to anything with Django
Edit 7/11/2011 I've added documentation and an example app. Introduction I'm writing this post to introduce a new project I've released, django-generic-m2m, which as its name would indicate is a generic ManyToMany implementation for django models. The goal of this project was to provide a uniform API for both creating and querying generically-related content in a flexible manner. One use-case for this project would be creating semantic "tags" between diverse objects in the database. Connecting Models What its all about is connecting models together and, if you want, creating some metadata about the meaning of that relationship (i.e. a tag). To this end, django-generic-m2m does three things to make this behavior easier: wraps up all querying and connecting logic in a single attribute that acts on both model instances and the model class allows any model to be used as the intermediary "through" model provides an optimized lookup when GenericForeignKeys are used An example Referring back to the diagram, let's create some models (these are the same models used in the testcases): from django.db import models from genericm2m.models import RelatedObjectsDescriptor class Food(models.Model): name = models.CharField(max_length=255) related = RelatedObjectsDescriptor() def __unicode__(self): return self.name class Beverage(models.Model): # ... same as above class … -
My Django tutorial at PyCon
Working on my tutorial slides for my PyCon class/tutorial/workshop last night I suddenly came to a stark realization.Out of dozens of slides, only 5 of them are Pinax specific.o.OI think this is because the slides are a condensed version of what the best and brightest in the Django and Python community think are good practices and tools. What do I mean?Jacob Kaplan-Moss on matching best practices with incredible documentation and tests.James Bennett on using small apps rather than monolithic ones.James Tauber and Brian Rosner's code in Pinax which taught me and so many others incredible Django tricks.PEP-8Zen of PythonMark Ramm on well, nearly everything but especially his critical commentaries on Django.So what does this mean?Well, I've been rethinking the mantra "Pinax is Django". It is hard to say that when users of django-cms and satchmoproject and other frameworks can't use core Pinax components. That said, users of those tools tend to rely on same foundation: Python, Django, virtualenv, and pip and growing ecosphere of Django Packages.Which leads me to realize that with just 5 slides pertaining to Pinax material in the tutorial, the Pinax Solutions class could be renamed "Django Solutions class with a bit of Pinax".And this makes a lot of … -
Renombrar nombres de archivos a ASCII
Los archivos que suben los usuarios a veces tienen nombres con caracteres no ASCII. Hoy en día casí todos los sistemas de archivos permiten encoding UTF-8, pero a veces nos podemos encontrar problemas en sistemas que no tienen UTF-8 activado o al ejecutar scripts sobre los ficheros que esperen un nombre de archivo en ASCII. Bojan Mihelac ha publicado en su blog una clase de almacenamiento que se basa en FileSystemStorage original añadiéndole la normalización de nombres de archivo a ASCII antes de ser almacenados. -
Announcing django-activitysync
Today I’m happy to announce the release of my first reusable Django app, django-activitysync. The app allows easy integration of social network activities and status updates into Django projects. I’ve been using it to power the activity section of this website for the past year and have been eager to decouple it into a separate application. What it provides Django-activitysync can provide functionality similar to other lifestream solutions, but its real power is as an extensible framework for aggregating, storing, and displaying any type of simple item. It currently provides built-in support for Twitter status items, Twitter searches, Google Reader shared items, and Reddit liked items. Adding support for a new network or activity type is as simple as implementing a new activity provider. Providers consist of 5 functions, one of which returns a list of simple objects containing the activity detail. Django-activitysync takes care of storage and duplicate detection. How to use it Django-activitysync is available as an installable Python package on PyPI. You will also find detailed documentation there on installation, configuration, and use. The source code itself is also available in a GitHub repository. Future plans This announcement marks the initial release of django-activitysync. I plan to … -
Announcing django-activitysync
Today I'm happy to announce the release of my first reusable Django app, django-activitysync. The app allows easy integration of social network activities and status updates into Django projects. I've been using it to power the activity section of this website for the past year and have been eager to decouple it into a separate application. What it provides Django-activitysync can provide functionality similar to other lifestream solutions, but its real power is as an extensible framework for aggregating, storing, and displaying any type of simple item. It currently provides built-in support for Twitter status items, Twitter searches, Google Reader shared items, and Reddit liked items. Adding support for a new network or activity type is as simple as implementing a new activity provider. Providers consist of 5 functions, one of which returns a list of simple objects containing the activity detail. Django-activitysync takes care of storage and duplicate detection. How to use it Django-activitysync is available as an installable Python package on PyPI. You will also find detailed documentation there on installation, configuration, and use. The source code itself is also available in a Bitbucket repository. Future plans This announcement marks the initial release of django-activitysync. I plan to … -
Monitoring Django with Munin
My friend and fellow Djangonaut Richard Barran, has written an excellent post about how to monitor a Django site using Munin. He’s written a couple of munin pluggins specifically for Django which he explains in the post. Essentially, Munin is a monitoring tool that lets you look at various performance aspects of your server, and is handy [...] -
Rutas relativas en los settings
Utilizar rutas relativas en nuestro settings.py en lugar de rutas absolutas permite que el proyecto no dependa del lugar en el que se encuentra en el sistema de archivos. Esto es ideal cuando utilizamos el proyecto en distintos entornos y las rutas absolutas del proyecto son distintas en cada uno de ellos, o si la ruta del proyecto puede variar en algún momento. -
Traducciones de modelos con django-transmeta
django-transmeta es una aplicación reusable que nos permite añadir traducciones a los campos de nuestros modelos. Es muy fácil de utilizar ya que crea automáticamente un campo en la base de datos por cada atributo traducible y cada idioma de nuestro setting LANGUAGES. Así, si tenemos un campo llamado nombre y nuestro setting LANGUAGES son inglés y español django-transmeta creará los campos nombre_es, nombre_en en la base de datos y al acceder directamente a atributo nombre obtendremos la traducción correspondiente al idioma que esté activo en la petición. -
My Pinax Solutions class at Pycon 2011
Heavily inspired by Zed Shaw's Learn Python the Hard Way class I'm changing the lecture style format of the Pinax Solutions class at PyCon 2011 to a more workshop-oriented format.Which means that the first half of the class we (myself and the peerless Brian Rosner) will spend on material critical for people new to Pinax or old hands who want to see what 0.9 offers. That means setting things up via virtualenv and pip, Pinax specific settings, media handling, template layout, extending core Pinax apps, use of idios to change profiles, openid/openauth, Django Packages to find Pinax approved stuff and more. That will be the foundation and our slides/handouts will be useful as cheat sheets for these critical parts in any Django application.The second half of the class will be a workshop. We'll spend the next half helping people with their personal projects, and will even have a few stock projects we can toss at people that either already are open source or could be released as open source. We won't write your project for you, but we will provide advice, guidance, and some elbow grease in getting things to work. If someone asks for something that we think the rest of the class could benefit … -
Utilizar jQuery en el admin de Django
Al personalizar alguna plantilla del sistema de administración podemos querer usar jQuery. Como el admin de Django ya hace uso de jQuery podemos utilizarlo directamente sin necesidad de incluir la propia librería. Pero enseguida nos daremos cuenta de que no podemos utilizar el alias $ ya que el admin utiliza la opción noConflict de jQuery. El alias que define el sistema de administración para usar jQuery es "django.jQuery". -
Django-admin-tools, la django app de janvier, presque à l’heure
Jusqu'à présent j'avais toujours réussi à poster mes billets de django app à l'heure. Mais là , là , j'ai une excuse. Je suis devenu papa le 31 janvier. Du coup, je n'ai vraiment pas eu le temps pour écrire mon billet de django app (les raleurs qui me diront que j'avais tout les jours d'avant ... -
Serving static files for Django on Webfaction
In my last post I wrote about the setup of Django with virtualenv on the Webfaction hosts. The post did not cover the serving of static files and will be covered here. It's always better to serve static media through an extra HTTP server/container doing nothing but serving static media files for better scaling. Normally I use nginx for this as it is small and fast. For Webfaction hosting you have two possibilities: You can add a "Static only" application that is an nginx, configure it for a separate (sub)domain and then configure your Django project to use this domain for serving the files. Wasn't that easy! Or you can use the Apache for serving the files. Create the "media" folder somewhere on your server (e.g. within the virtualenv folder: /home/<username>/webapps/<wsgi-app>/<virtualenv-dir>/media). Now adjust the apache.conf to load the modules required for serving the media and set some expiration time if you like (I used 12 hours as seen below). I'm only writing the updates to the apache.conf of the last post: EDIT: had to temporarely disable the snippet, as the host does not answer. Please check for yourself: snipt.org/embed/wmkmm -
Serving static files for Django on Webfaction
In my last post I wrote about the setup of Django with virtualenv on the Webfaction hosts. The post did not cover the serving of static files and will be covered here. It's always better to serve static media through an extra HTTP server/container doing nothing but serving static media files for better scaling. Normally I use nginx for this as it is small and fast. For Webfaction hosting you have two possibilities: You can add a "Static only" application that is an nginx, configure it for a separate (sub)domain and then configure your Django project to use this domain for serving the files. Wasn't that easy! Or you can use the Apache for serving the files. Create the "media" folder somewhere on your server (e.g. within the virtualenv folder: /home/<username>/webapps/<wsgi-app>/<virtualenv-dir>/media). Now adjust the apache.conf to load the modules required for serving the media and set some expiration time if you like (I used 12 hours as seen below). I'm only writing the updates to the apache.conf of the last post: ... # put after other LoadModule lines LoadModule alias_module modules/mod_alias.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule expires_module modules/mod_expires.so ... <VirtualHost *:1234> ... # after WSGIScriptAlias Alias /media /home/your_user_name/webapps/your_wsgi_app_name/virtualenv_directory/media/ <Directory /home/your_user_name/webapps/your_wsgi_app_name/virtualenv_directory/media> Order … -
Serving static files for Django on Webfaction
In my last post I wrote about the setup of Django with virtualenv on the Webfaction hosts. The post did not cover the serving of static files and will be covered here. It's always better to serve static media through an extra HTTP server/container doing nothing but serving static media files for better scaling. Normally I use nginx for this as it is small and fast. For Webfaction hosting you have two possibilities: You can add a "Static only" application that is an nginx, configure it for a separate (sub)domain and then configure your Django project to use this domain for serving the files. Wasn't that easy! Or you can use the Apache for serving the files. Create the "media" folder somewhere on your server (e.g. within the virtualenv folder: /home/<username>/webapps/<wsgi-app>/<virtualenv-dir>/media). Now adjust the apache.conf to load the modules required for serving the media and set some expiration time if you like (I used 12 hours as seen below). I'm only writing the updates to the apache.conf of the last post: ... # put after other LoadModule lines LoadModule alias_module modules/mod_alias.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule expires_module modules/mod_expires.so ... <VirtualHost *:1234> ... # after WSGIScriptAlias Alias /media /home/your_user_name/webapps/your_wsgi_app_name/virtualenv_directory/media/ <Directory /home/your_user_name/webapps/your_wsgi_app_name/virtualenv_directory/media> Order … -
Serving static files for Django on Webfaction
In my last post I wrote about the setup of Django with virtualenv on the Webfaction hosts. The post did not cover the serving of static files and will be covered here. It's always better to serve static media through an extra HTTP server/container doing nothing but serving static media files for better scaling. Normally I use nginx for this as it is small and fast. For Webfaction hosting you have two possibilities: You can add a "Static only" application that is an nginx, configure it for a separate (sub)domain and then configure your Django project to use this domain for serving the files. Wasn't that easy! Or you can use the Apache for serving the files. Create the "media" folder somewhere on your server (e.g. within the virtualenv folder: /home/<username>/webapps/<wsgi-app>/<virtualenv-dir>/media). Now adjust the apache.conf to load the modules required for serving the media and set some expiration time if you like (I used 12 hours as seen below). I'm only writing the updates to the apache.conf of the last post: ... # put after other LoadModule lines LoadModule alias_module modules/mod_alias.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule expires_module modules/mod_expires.so ... <VirtualHost *:1234> ... # after WSGIScriptAlias Alias /media /home/your_user_name/webapps/your_wsgi_app_name/virtualenv_directory/media/ <Directory /home/your_user_name/webapps/your_wsgi_app_name/virtualenv_directory/media> Order … -
Getting started with WTForm
I found out that Clint mentioned the little pet project of mine on his weekly roundup of happenings in the Django world. So I thought this would be a great time to tell the world a bit more about the project, and do a little practical example for the readers. What does WTForm do? Basically, WTForm does the following: Widget and Field type as class names on field container div for easier CSS styling. (and a required indicator as well) Allows you to group your form fields and columns in fieldsets. Allows you to group your form fields and fieldsets in columns. (oh - the redunancy!) With regard to the last two points, WTForm allows for "infinite" nested structures. Enables you to insert arbitrary HTML snippets in the middle of your form. Project background The project was started as small hack when we (at GMTA) needed another output scheme (namely using div tags) and needed to allow for easier CSS styling using classes on every container div tag. The problem is that the "vanilla" newforms will output the form without any classes indicating whether the field is required or what kind of field we are working with. This resulted in … -
Using decorators in Django views to assert the DRY principle
A lot of people finds decorates to be pure magic. I will try to de-mystify some of the magic around them, and show how we can use them to clean up the views in a Django application. I will start by giving a short introduction to decorators and closures and then afterwards show how we can use this in Django to, as the title says, assert the DRY (dont repeat yourself) principle So, what is a decorator? A decorator is a closure. That is, a set of local variables (an evironment) and some code (in this case, a function) to be executed in this environment. A small example of a simple closure: def adder(n): def inner(m): return n + m return inner When a call to adder is made, a new function is returned. This function has one local variable (n) already and takes another one as an argument (m). An example use could be: >>> add_five = adder(5) >>> add_five(37) 42 In Python, it's very popular to say that everything is an object and can be tangled with. This is also the case of functions. When defining a function, all you really do is defining a variable pointing to … -
Managing local settings in Django
Sometimes it is nice to be able to configure specific Django settings for a single host and not get tons of conflicts the next time you do svn up. I personally solve this by exploiting that the Django settings.py is nothing but Python code. At the last line of the file I do a: from local_settings import * That is, way I do a relative import from local_settings.py and gets every global symbol mixed into the current namespace, allowing me to overwrite every option. An example could be to configure the global settings.py to use sqlite as a database backend for the project, but in the production environment overwrite the DATABASE_* options in the local_settings.py. This goes as well for caching - not many developers run a PostgreSQL and memcached on their laptop. To make sure that local_settings.py never is committed to the repo (and maybe compromising database passwords), it is a good idea to add it to the Subversion property svn:ignore: svn propset svn:ignore local_settings.py /path/to/your/project Furthermore, I usually put up a local_settings.py.dist with a couple of commented out examples for the developers of what could be done here. -
Rolling your own simple authentication system for Django
Sometimes you need to roll a simple authentication system for Django. For example, I just hacked a client interface on our corporate intranet at GMTA, using a similar approach as the one I will describe here. The solutions consists of four parts: Extending the model to include a password Login form Login / Logout views A login_required decorator for views to require authentication Extending the model In order for us to authenticate a Client we need to add a password to the model. As it is not good practice to store passwords in plain text in the database, we will store the password as a salted hash. In this example I will use the SHA-1 secure hash function. We will add two functions to the Client model in order to handle the hashing itself. This is also helpful if we later in the project decides to change the hashing algorithm used. The two functions and the password field: password = models.CharField(maxlength=40) def update_password(self, new_password): self.password = sha.new(settings.PASSWORD_SALT + new_password).hexdigest() def check_password(self, password): hsh = sha.new(settings.PASSWORD_SALT + password).hexdigest() return hsh == self.password In order to update the password for a Client we just call the update_password method - as well as … -
Filtering foreign key choices in newforms-admin
I decided it was time to learn something about the newforms-admin branch of Django, so I set out to try to write a couple of simple models for administering a mail server (something we always needed at GMTA, but I have never really liked any of the currently available options). Here is the models so far: class Customer(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() def __str__(self): return self.name class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) customer = models.ForeignKey(Customer) class Domain(models.Model): name = models.CharField(max_length=100) customer = models.ForeignKey(Customer) def __str__(self): return self.name def save(self): # When a user adds a Domain, save the current customer. if not self.id: self.customer = get_current_user().customer_set.all()[0] # Call the super save method super(Domain, self).save() class Mailbox(models.Model): name = models.CharField(max_length=100) domain = models.ForeignKey(Domain) password = models.CharField(max_length=100) def __str__(self): return '%s@%s' % (self.name, self.domain) class Meta: verbose_name_plural = "mailboxes" class Alias(models.Model): name = models.CharField(max_length=100) domain = models.ForeignKey(Domain) destination = models.EmailField() def __str__(self): return '%s@%s -> %s' % (self.name, self.domain, self.destination) class Meta: verbose_name_plural = "aliases" Model notes There is a few gotchas in the above model code: Remember to add AUTH_PROFILE_MODULE to your settings. See the Django Book on user profiles for details. I use a thread locals hack to … -
New WTForm release
I have just published a new version of WTForm, my Django newforms addon to allow for grid form layouts (using YUI) and extra classes for more specific and easier CSS styling. There was a problem when using WTForm with form_for_model or form_for_instance resulting in not getting any fields in the generated form class. This should be fixed now. The djangosnippets page for WTForm now also includes a link for a screenshot to see an example of a form using grids and some other neat CSS styling by my colleague Oscar. -
M2m, tout petite astuce
Il faut parfois utiliser des m2m. Dans django, il y a deux moyens de les utiliser. Soit d'une façon simple, en déclarant juste un ManyToManyField soit en passant par une table explicite grâce à l'argument through. L'argument through permet d'avoir une table explicitement déclaré que l'on peut donc manipuler avec l'ORM. Mais si on utilise la ... -
How to sell Python panel at Pycon
Do you want to use Python but are you fighting Fear, Uncertainty, and Doubt (FUD) in your organization? Does any of this sound familiar to you?Python is just a scripting language.Python is too new to use in real production environments.Language X has better benchmarks doing obscure math so it is better for web development.Python sounds great but we've already spent so much on this expensive tool that does things badly!A lot of people want to use Python, but their customer, management, school, government, or organization won't let them. Python is a great tool, but can be challenging to get in the door. This panel will explore how companies and individuals have successfully introduced Python, what tools are available to sell Python, how to fight the good fight, and what pitfalls there are to avoid.Panel QuestionsFor this event at Pycon I've got some stock questions ready but I want the community at large to suggest some more.SpeakersFor this panel I choose five speakers from the broad categories of academia, government, commercial organizations, and non-profit who have had a known impact in their organizations:AcademiaC. Titus Brown is an Open source hacker, Artificial Life/Digital Evolution, B.A. Math (Reed), Earthshine research, Ph.D. Developmental Biology and Regulatory genomics (Caltech), …