Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Sprint de de Traduccion de documentacion de django terminado
Este fin de semana fue el sprint de traduccion de la documentacion de django al español. La verdad fue muy bueno participar e intentar retribuir de cierta manera todo lo que este framework nos dio. Me senti peculiarmente emocionado de estar entre la lista de los colaboradores. Ayer terminó el sprint de traducción. En estos [...] -
StdImage updated to trunk
Everything is changing on Django those days, and many people contacted me because StdImage stopped working with trunk.Basically all major changes (except GeoDjango) affected it, such as change from newforms to forms, signal refactoring, and file storage refactoring. Now it's up to date.Remind that django-stdimage is a Django application that provides a standardized image field(standard name including row id, standard size, and ability to create automatic thumbnails, also standarized of course). -
Translating Django apps. Good practices
In this article you'll find some tips, that could be useful for avoiding problems or extra work when translating your Django application.1. Setting up the environmentDoing some trivial changes to your project structure, can avoid you of translating many string (the ones that are already translated in Django, or in any external application).For achieving it, my tip is to copy Django itself, and all external applications to your project path, not in a PYTHONPATH directory. It can also avoid compatibility problems, and version conflicts if you're working on several projects. Then your project root will contain something like:__init__.pysettings.pyurls.pydjango/transdb/myapp/Next step is patching Django (while it's not included in trunk) to omit the inclusion of already translated applications into your project. Here is the patch, and you can also see #7050 for further information, or know the status.Then, when executing ./manage.py makemessages you'll find in your project catalogs, just strings that aren't previously translated.2. Creating stringIf you don't have a correct literal creation policy, then your translator will have extra work, problems, and your translation won't be as correct as it should.The first thing to do is write literals thinking in reusability (as software reusability but for translations). I'll show it with … -
DSNP 0.9 released
I know that it was just few days ago that I released another version of DSNP, but because of it, I got a lot of feedback on it, I worked hard, and finally DSNP is stable.For now, it'll be 0.9 because it works on Django newforms-admin branch, so 1.0 will be reached when newforms-admin will be merged into trunk.Changeset for this version is next: Generated sqlite file has write permissions for all users by default Static files are served by Django http server on development environment (DEBUG==True) File admin.py created to specify admin options Media path has changed (now, all static files are under "media" directory) due to an issueI hope you like it. -
DjangoCon is still alive?
On July 13th, DjangoCon 2008 was announced, and the illusion and nervousness started for many djangonauts. The main problem here, is that due to the lack of time and experience, the number of attendees is limited to 200. That makes sense, but there are other things that doesn't make sense to me. This post is about that, and it's intended to be a kind of constructive criticism.The fact is that many people is waiting to know if he/she can get a ticket to start planning the trip to SF, ans specially to purchase flight tickets. In those two weeks since DjangoCon announcement, flight prices from Barcelona to SF have increased in a 30%. I don't think it's the only case.My question is... It is so difficult to develop and run an application to register users, letting many djangonauts to save some money that could be given to the DSF? :) Are you coding it in PHP? ;)Seriously, if you need help, just ask for it, we are a community. But please, stop delaying ticket releasing, we have to get our tickets, make our plans, and we don't want to waste our money getting last time flight tickets. IMHO ticket realising … -
Changing language on the admin
When working on multilanguage sites, a feature that many times I missed is a direct way to change the language when you're on the admin,With standard Django the only way that exists (as far as I know), is leaving the admin, going to the website, change the language there, and come back to the admin. Not very fast.Today, I've created a snippet that creates a drop down menu on the admin bar (just in the main page) to change the language.Hope it helps. -
StdImageField: Improved image field for Django
I'm pleased to announce a new project, django-stdimage, that provides a new image field with many improvements respect to Django's core ImageField.Features of StdImageField: Saved files have standardized names (using field name and object id) Images can be removed Automatically creates a thumbnail Automatically resizes both image and thumbnail (with optional crop to fit exactly specified size)Here you've an example of usage:from django.db import modelsfrom stdimage import StdImageFieldclass MyClass(models.Model): my_image = StdImageField(upload_to='path/to/img', blank=True, \ size=(640, 480), thumbnail_size=(100, 100, True))If a file called "uploaded_file.png" is uploaded for object id 34, then result will be: /path/to/img/my_image_34.png (with bigger possible size to fit in a 640x480 area) /path/to/img/my_image_34.thumbnail.png (with a exact size of 100x100, cropping if necessary)Also it will appear a check-box for deleting when using admin. -
TransDb working on trunk!
Some days ago, after the merge of qs-rf to trunk, model field i18n was in trouble, so the principal package for this approach (django-multilingual) stopped working for the latest version of trunk.This weekend we had a TransDb sprint, to try to improve our project, and contribute to fix this situation in any way.The result: We fixed many issues on TransDb, now the project has a more conventional structure, and a setup script, and... TransDb is now working on trunk!For achieving it we created a new branch called oldforms.Try it now! -
Searching on Django Snippets
One of the key websites about Django is Django Snippets, by one of the key Django developers, James Bennett.I've followed many of the James work, and it's awesome; but I've a complaint on Django Snippets. It's the inefficient way to find anything there. The only ways that I've found is searching using a paginated list by author, language or tag (sorted alphabetically), where you can spend a huge amount of time if the tag you search starts by Z.Of course that I can go to Google an search using site:www.djangosnippets.org, and it would work for all indexed snippets, but I think that at least this search box should be added on the site (until anybody writes the generic search engine for Django). It would also help adding result page numbers (with links) at the end of the paginated list. -
Unable to define my urls exactly my way (resignation statement)
I've been working with Django for a while, and it helped me to get all my web developments with nice urls. But I also wanted a nice url structure...What it is nice for me, opposite to Django default settings, is avoiding the media prefix on my media urls, sohttp://localhost/media/admin/css/login.css would be http://localhost/admin/css/login.cssTrying to emulate old website structures (used widely in php sites).That could be nice or not, but for sure it is complicated.The first step was to setup apache for it, a little bit more complicated than the usual setup, but possible:<LocationMatch "/((css|js|img|swf|pdf)/|favicon.ico)">SetHandler None</LocationMatch>The main problem comes when using Django development http server (started by "python manage.py runserver"), and the admin. Of course you can do that, but what is not possible, is to define the same name for your admin media path, and for the admin itself.For example:http://localhost/admin and http://localhost/admin/css/login.cssThe reason is the Django web server, processes all requests starting with the ADMIN_MEDIA_PREFIX setting with the AdminMediaHandler, what implies with that structure that all admin requests (even the ones that aren't static files) are processed by this handler, raising an error when the request isn't for a static file. The error is next.Permission denied: ${PYTHON_PATH}/django/contrib/admin/media/So this is my resignation … -
Django L10n
This Sunday, I participated in This Week in Django, and tried to give some ideas on Django localization.Here I'll post some of the ideas of the interview (and some that I missed), for serving as reference:How to translate your application (quick guide): Mark every text in your application for translation: In models.py, views.py... convert 'my text in just one language' to _('my text to translate'). Don't forget to import _: from django.utils.translation import ugettext_lazy as _ In templates, convert <p>Text in english</p> to <p>{% trans 'Text in many languages' %}</p> (also this can be done with blocktrans tag) Go to your project path and create a directory called locale (also you can do that just for an application) Execute ${PATH_TO_DJANGO}/bin/make-messages -l ${LANGUAGE_CODE} (where language code is en for english, es for spanish...) Edit ${PROJECT_PATH}/locale/${LANGUAGE_CODE}/LC_MESSAGES/django.po and set the msgstr variables with the translation of every msgid Run msgfmt django.po -o django.mo (I just realized after the interview that exists a django script complie-messages.py that does that for all .po files) And then you have your application translated. There are some settings in settings.py that need to be set for making it work (USE_I18N = True, set LANGUAGES and LANGUAGE_CODE, and specify … -
TransDb: Django’s i18n for database
Today I've created my own code for having (in Django) fields in more than one language stored in database. There were some other packages, but none of them useful for me (as commented here).TransDb's main goal is that is simple, for application users, application programmers, and the code itself. Some work is still missing, but there is a working version at TransDb Google Code page.Any comment will be appreciate. -
New DSNP version
DSNP is a simple and customizable Python script, that automatically creates a working Django project.Project (and application) creation in Django are very openend and flexible, but sometimes is useful getting all the work done for you, specially: If you create many Django projects with the same structure. If you're new to Python, and want to see a "hello world!" application working in less than one minute. If you want to check your Django structure with somebody's else (me).DSNP does exactly that, automates the process of creating projects and applications in Django. The resulting website is a simple project with a single application, ready for start creating models and templates. It's also customizable, to let everyone set their own preferences in the script, and adapt it to your desired structure.Want to try it (in five simple steps)?svn checkout http://dsnp.googlecode.com/svn/trunk/python dsnp.py myprojectcd myprojectpython manage.py runserverBrowse http://localhost:8000/ Easy right? -
Media data without media directory
It's not a big trouble, but I wanted to remove the /media/ prefix on all my media links, like...<img alt="My Image" src="/media/img/myimage.png"/><link rel="stylesheet" href="/media/css/mysheet.css" type="text/css"/>and so on.This can be easily achieved by replacing in apache's configuration file:<Location "/media/">SetHandler None</LocationMatch>by<LocationMatch "/((css|js|img|swf|pdf)/|favicon.ico)">SetHandler None</LocationMatch>Of course you have to have all you media files in folders like css, js, img... or anything that you specify in last regular expression.UPDATE: See this post before using this approach. -
Normalize name and size images in Django (and adding thumbnails)
I wanted to assign an image to every element in a model. I wanted them to have a thumbnail, and to have normalized sizes and names. And of course, I want my application to do everything automatically.The best method I've found is next, modifying models.py (note that PIL must be installed):def rename_image(src, field, id): file_ext = os.path.splitext(src)[1].lower().replace('jpg', 'jpeg') dst = 'img/uploaded/work_%s/%s_%s%s' % (field, field, id, file_ext) return dstdef resize_image(src, dst, size): from PIL import Image image = Image.open(src) image.thumbnail(size, Image.ANTIALIAS) image.save('%s%s' % (settings.MEDIA_ROOT, dst)) return dstclass MyModel(models.Model): image = models.ImageField(upload_to='img/uploaded/work_image', verbose_name=_('imagen')) thumbnail = models.ImageField(editable=False, upload_to='img/uploaded/work_thumbnail') [...] def save(self): super(MyModel, self).save() if self.image != rename_image(self.image, 'image', self.id): original_filename = self.get_image_filename() self.thumbnail = resize_image(original_filename, rename_image(original_filename, 'thumbnail', self.id), [100, 75]) self.image = resize_image(original_filename, rename_image(original_filename, 'image', self.id), [640, 480]) if os.path.exists(original_filename): os.remove(original_filename) super(MyModel, self).save() -
TransDb: Pretty much easier
Today I've released a new version of TransDb, the Django package that allows storing text at database in more than one language (using the same field).New version is pretty much easier to use, after fixing many bugs, and avoiding the use of a filter in templates.Now, migrating your single-language application to a multi-language one is very easy, so almost the only thing you've to do is changing your model fields (no data transformation is required, it is done automatically when you translate texts at admin). A full migration procedure is available at project page.You can find everything at Google's project page. -
Django Catalan usergroup meeting
Six months ago, I decided to create the Django Catalan usergroup, for user in Catalonia, and for users who speak catalan.Today I'm happy to announce that we are already 26 members, and we are going to have our first meeting on April 3rd. We've decided to meet together with people from The Barcelona Python Meetup Group, so both groups have common interests, and many people in common.Our planning is having some talks on key subjects such as "Django presentation to non-Django users", "Django status", "Django i18n", "Python 3k"... as well as lightning talks from everybody, to share personal or professional experience with Python/Django. We'll also discuss about organizing a conference in Barcelona, and about the Django-Rails football (aka soccer) match.If you are in Barcelona on 3rd, and you want to join us, here you have details (remember that attendance confirmation is required one day before the event):http://python.meetup.com/185/calendar/7640211/See you there! -
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 -
Second editions galore
Adrian announced today that he’s working on revising The Definitive Guide to Django to produce a second edition that covers Django 1.0, which is awesome news for anyone who’s used the book as a guide to learning Django. In the same vein, I’d like to announce something that’s been unofficially mentioned a couple times but never fully clarified: I’m busy working on the second edition of Practical Django Projects, which will also cover Django 1 ... Read full entry -
Second editions galore
Adrian announced today that he’s working on revising The Definitive Guide to Django to produce a second edition that covers Django 1.0, which is awesome news for anyone who’s used the book as a guide to learning Django. In the same vein, I’d like to announce something that’s been unofficially mentioned a couple times but never fully clarified: I’m busy working on the second edition of Practical Django Projects ... Read full entry and comments -
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__ …