Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
PyCon Wrapup
With PyCon now over for me(and the sprints just begining for those still there) I figured I'd recap it for those who couldn't be there, and compare notes for those who were. I'll be doing a separate post to cover my panel, since I have quite a brain dump there.Day OneWe start off the morning with lightning talks, much better than last year due to the removal of so many sponsor talks(thanks Jacob), by now I've already met up with quite a few Django people. Next I move on to the "Python for CS1" talk, this was particularly interesting for me since they moved away from C++, which is exactly what my school uses. Next, on to "Introduction to CherryPy" with a few other Djangonauts. CherryPy looks interesting as a minimalist framework, however a lot of the callback/plugin architecture was confusing me, so I feel like I'd be ignoring it and just being very close to the metal, which isn't always a bad thing, something to explore in the future. For there I'm off to "How Python is Developed", it's very clear that Django's development model is based of Python's, and that seems to work for both parties.Now we head … -
Some quick updates
It's been a busy and exciting week for us. Jacob has been at PyCon in Chicago where he is participating in a number of panel discussions and giving quite a few talks as well. Right now I imagine he's neck deep in code in the Django sprint helping to finish up the upcoming 1.1 release. If you're running a production site built with Django you should absolutely check out the talk he is giving with James Bennett on Real World Django. While my week has been busy hacking away on several client projects and moving my main work machine to a shiny new MacBook Pro (can't recommend these highly enough), I was interviewed by Daniel Dern of Business Trends Quarterly in his post about scaling and performance titled For Scaling, Brains May Beat Brawn. We talk about how just throwing more money and hardware at a problem is not always the best solution. Often there are architectural, design, and/or configuration changes that can bring significant cost savings to your project. Both in terms of the hardware necessary to keep everything flowing, but also in on going system maintenance labor costs. I'm not talking about pre-optimization evils or complicating things … -
Using svn:externals for external Django module dependencies
After working on building a fairly complex Django application for the last year or so, I have ended up using a few of the open source Django modules that are out there. Why re-invent the wheel after all? Most of these projects are thankfully hosted on Google Code which uses Subversion as the source control system. [...] -
PyCon ORM panel liveblog
I’m sitting about five rows back in the ballroom at the Hyatt, waiting for the ORM panel to begin. Panel’s starting. Moderator Alex Gaynor introduces himself and panelists: Guido van Rossum (App Engine) Jacob Kaplan-Moss (Django) Massimo diPierro (web2py) Ian Bicking (SQLObject) Mike Bayer (SQLALchemy) First question: brief history of your ORM SQLALchemy: wanted to do a CMS, but never ended up writing it. Had idea for a modular library to talk to databases, different bits you could ... Read full entry -
PyCon ORM panel liveblog
I’m sitting about five rows back in the ballroom at the Hyatt, waiting for the ORM panel to begin. Panel’s starting. Moderator Alex Gaynor introduces himself and panelists: Guido van Rossum (App Engine) Jacob Kaplan-Moss (Django) Massimo diPierro (web2py) Ian Bicking (SQLObject) Mike Bayer (SQLALchemy) First question: brief history of your ORM SQLALchemy: wanted to do a CMS, but never ended up writing it. Had idea for a modular library to talk to ... Read full entry and comments -
A Noob In King Guido's Court
Here I am, somehow, impossibly, in Chicago and attending PyCon. Somewhere in this crowd are other Djangonauts. I need to figure out how to find them. -
sorl.thumbnail and Custom Processors
In the past few months, sorl.thumbnail has become one of the standard libraries I always include in my Django projects. It’s unobstrusive and very easy to implement into templates, but my one grief with it has been the lack of capability for doing some custom processing on images. As it turns out, sorl actually allows custom processors to be added. When I found out about this feature, I set out to write some for my current project. If you haven’t heard about the processors functionality, it’s all in the documentation. I am not sure how I missed it before. Implementing is pretty easy, first you have to define a THUMBNAIL_PROCESSORS variable in your settings.py file: THUMBNAIL_PROCESSORS = ( 'sorl.thumbnail.processors.colorspace', 'sorl.thumbnail.processors.autocrop', 'sorl.thumbnail.processors.scale_and_crop', 'sorl.thumbnail.processors.filters', 'imagery.processors.pad', 'imagery.processors.round',) The first four are obviously sorl’s own default processors. The last two are my custom ones. “pad” allows resizing without cropping, while keeping the final image dimensions always the same. So basically it centers the resized image in an area and fills the rest of the image with a given background colour: from PIL import Image THUMBNAIL_PADDING_COLOUR = (255, 255, 255) def pad(im, requested_size, opts): """ Adds padding around the image to match the requested_size """ if "pad" … -
Django 1.1 beta
Как многие, без сомнения, знают, недавно вышла Django 1.1 beta. Там в release notes все самое вкусное перечислено, а я немножко вокруг покомментирую. Одна из когда-то давно слезно просимых фич -- загрузка объектов с неполным списком полей (aka "defer/only"). Раньше это делалось через .values(), но результатом запроса был тупой набор значений. Новая фича возвращает полноценные объекты с недозаполненными полями. Поля заполняются отдельными запросами при первом обращении. Теперь, по меткому выражению Малколма все кинутся этим пользоваться, потому что оно кажется очень крутым. Грустная ирония состоит в том, что если вы думаете, что вам нужны defer/only, это с высокой вероятностью либо преждевременная оптимизация, либо указание на неудачную модель базы. То есть, либо вы Реально Большие BLOB'ы храните в базе, вместо файлов, либо у вас в модели куча полей, которые можно и нужно разнести по разным моделям, провязанным один-к-одному. Впрочем, ладно, разберемся :-) Еще одна фичка, про которую я даже не знал, пока в релиз нотах не прочитал -- массовые действия над объектами в админке. Тоже давно просили все, чтобы массово что-нибудь удалять или проставлять флажки всякие. Что меня реально порадовало -- это то, что фича сразу вышла хорошо проработанной в деталях: можно выдать юзеру свое сообщение типа "удалено столько-то объектов" можно вместо … -
Django 1.1 beta
Как многие, без сомнения, знают, недавно вышла Django 1.1 beta. Там в release notes все самое вкусное перечислено, а я немножко вокруг покомментирую. Одна из когда-то давно слезно просимых фич — загрузка объектов с неполным списком полей (aka "defer/only"). Раньше это делалось через .values(), но результатом запроса был тупой набор значений. Новая фича возвращает полноценные объекты с недозаполненными полями. Поля заполняются отдельными запросами при первом обращении. Теперь, по меткому выражению Малколма все кинутся этим пользоваться, потому что оно кажется очень крутым. Грустная ирония состоит в том, что если вы думаете, что вам нужны defer/only, это с высокой вероятностью либо преждевременная оптимизация, либо указание на неудачную модель базы. То есть, либо вы Реально Большие BLOB'ы храните в базе, вместо файлов, либо у вас в модели куча полей, которые можно и нужно разнести по разным моделям, провязанным один-к-одному. Впрочем, ладно, разберемся :-) Еще одна фичка, про которую я даже не знал, пока в релиз нотах не прочитал — массовые действия над объектами в админке. Тоже давно просили все, чтобы массово что-нибудь удалять или проставлять флажки всякие. Что меня реально порадовало — это то, что фича сразу вышла хорошо проработанной в деталях: можно выдать юзеру свое сообщение типа "удалено столько-то объектов" можно вместо … -
Django 1.1 beta
Как многие, без сомнения, знают, недавно вышла Django 1.1 beta. Там в release notes все самое вкусное перечислено, а я немножко вокруг покомментирую. Одна из когда-то давно слезно просимых фич — загрузка объектов с неполным списком полей (aka "defer/only"). Раньше это делалось через .values(), но результатом запроса был тупой набор значений. Новая фича возвращает полноценные объекты с недозаполненными полями. Поля заполняются отдельными запросами при первом обращении. Теперь, по меткому выражению Малколма все кинутся этим пользоваться, потому что оно кажется очень крутым. Грустная ирония состоит в том, что если вы думаете, что вам нужны defer/only, это с высокой вероятностью либо преждевременная оптимизация, либо указание на неудачную модель базы. То есть, либо вы Реально Большие BLOB'ы храните в базе, вместо файлов, либо у вас в модели куча полей, которые можно и нужно разнести по разным моделям, провязанным один-к-одному. Впрочем, ладно, разберемся :-) Еще одна фичка, про которую я даже не знал, пока в релиз нотах не прочитал — массовые действия над объектами в админке. Тоже давно просили все, чтобы массово что-нибудь удалять или проставлять флажки всякие. Что меня реально порадовало — это то, что фича сразу вышла хорошо проработанной в деталях: можно выдать юзеру свое сообщение типа "удалено столько-то объектов" можно вместо … -
Python implementation details
I’m sitting here at PyCon at the Python Language summit discussing differences between Python versions, and the topic of implementation details came up. The main part of getting Django working on alternate Python VMs was fixing the various assumptions we made about implementation details of Python. I went back and dug through Django’s ticket tracker for the issues alternate VM issues (most from the Jython developers, some from the PyPy developers) that we had to fix; it’s a pretty instructive list of things you shouldn’t rely on if you’d like your Python code to run on alternate VMs: -
django-cart released!
Until now, if you had to develop an online store in django, you had two options, use satchmo, or write your own code. Satchmo is a huge application that tries to provide everything for all the cases, so for a simple shop you've to deal with hundreds of features that you're not going to use, and in some case it won't be enough flexible.So what I've not any complain for satchmo, the fact is that is not the ideal solution for some cases as some small shops with few options.With that said, this post is to announce the release of a new project that could help some people to do simple web shops in a very simple way. This project is django-cart.While django-cart already existed, it was an unfinished (and unmaintained) project by Eric Woundenberg, to whom I'm very thankful for letting reuse it's project, and avoid confusion.So, what's django-cart. Django Cart is basically a django application that provides a Cart class, with add/remove/update and get methods to be used for storing products. The products model isn't included in the application, so you can define your products with the fields you need. Then you just need something like...product_to_add = MyProductModel.objects.get(id=whatever)cart … -
StaticMap: A Google Maps API Wrapper
I love the Google Maps API, it’s fairly easy to use, well documented, has lots of features to tweak and extend beyond the obvious. However, it’s hefty. The initial load with map assets can easily total 300K, and visibly slow down your site especially if you are providing more than one map on a single page. So, to solve these issues I decided to write a thin layer around the Maps API. The idea is simple: a map doesn’t need to be interactive unless the user wants to interact with it. Unless your page’s sole focus is the map, it doesn’t make sense to load a fully featured interactive map every time the page renders. Google provides the Static Map API, which can generate an image-based map for you on request. It’s well documented, but building the URL for the image map can take a while, especially if you are putting markers on the map. That’s where my StaticMap class comes in. You simply instantiate it with a few options, and it generates the map for you: new core.StaticMap("#MapArea", { "api_key" : "<GOOGLE_MAPS_API_KEY>", "size" : [298, 298], "center" : [41.9288, -87.6315], "zoom" : 10, "markers" : [ { "coordinates" : … -
Fixtures, default data for your models
So, we started working on our project (finally) and although some of the requirements of the project will change in the course of the following days, we are working on the more general aspects of the site. Among these general “apps” is the help app. Basically it has a couple of static pages and then a hierarchy of categories (folders) and topics presented in a similar way to Google’s Gmail Help Page. This help app is a variation of the usual Polls or Books examples you get in Django’s Writing you first Django App Tutorial, and is a very good exercise to get up to speed with the development in Django. As the app started to take shape we began to wonder if Django provided a mechanism to load default data into the models… Fortunately it does! You can read all about loading initial data into models it in the docs, but if you want to continue reading about our experiences and choices, read on! In a nutshell: You can choose between two methods, fixtures or SQL. Fixtures are database agnostic representations of database rows in either XML, JSON, YAML, or Python objects notation. While SQL, you know, consists of … -
Django 1.1 beta lançado
Como parte do processo de lançamento do Django 1.1, essa noite nós lançamos o Django 1.1 beta 1, um pacote que traz algumas das novas funcionalidades que virão no Django 1.1. Assim como em todos os pacotes alpha ou beta, ele não deve ser usado em produção, mas se você gostaria de experimentar alguma das novidades do 1.1, ou se você gostaria de nos ajudar a consertar bugs antes do lançamento da versão 1.1 final (marcada para April), sinta-se a vontade para obter uma cópia e dar uma olhada. Você pode obter uma cópia do pacote 1.1 beta da nossa página de downloads, e nós recomendamos a leitura das notas de lançamento. Também, para os conscientes de segurança, checksums MD5 e SHA1 assinados do pacote 1.1 beta estão disponíveis. Nossa próxima parada será aPyCon Americana 2009 em Chicago onde, entre outras coisas, faremos sprints de desenvolvimento visando o release final do Django 1.1. Para um roadmap completo da versão, veja as notas de lançamento da versão alpha. Postado por Jacob Kaplan-Moss em 23 de Março de 2009, no blog do Django - Tradução por Walter Cruz -
TYPO3 performance
There are a few nice tipps in the blog of Dmitry Dulepov to speed up the Typo3 performance you should have read. #2 was unknown to me so far. -
TYPO3 performance
There are a few nice tipps in the blog of Dmitry Dulepov to speed up the Typo3 performance you should have read. #2 was unknown to me so far. -
TYPO3 performance
There are a few nice tipps in the blog of Dmitry Dulepov to speed up the Typo3 performance you should have read. #2 was unknown to me so far. -
Django Compress: New CSS Filter
I added a new filter today for django-compress that allows for arbitrary string find/replace during the compile process on your css groups. I had a specific use case for the new filter: my css had a lot of root relative urls for background images. I wanted to host my compiled media on a different host than where my images were being hosted from but this tied the two together. Furthermore, I didn't want to hard code the absolute urls as I want to be able to test the full environment on my laptop, test environments and finally be able to deploy somewhere else in production. I want the process of changing environments to be simple settings file change. Therefore, my approach was to create a filter that at compile time execute a string find and replace. It's super simple, but useful, at least to me. I also found what I think were a couple of bugs when you had some groups with external_urls defined. When they were missing source_filenames and output_filenames definitions, exceptions were raised when running the management command to compile the source. I put some simple checks in place to safe guard against these exceptions. -
Django Compress: New CSS Filter
I added a new filter today for django-compress that allows for arbitrary string find/replace during the compile process on your css groups. I had a specific use case for the new filter: my css had a lot of root relative urls for background images. I wanted to host my compiled media on a different host than where my images were being hosted from but this tied the two together. Furthermore, I didn't want to hard code the absolute urls as I want to be able to test the full environment on my laptop, test environments and finally be able to deploy somewhere else in production. I want the process of changing environments to be simple settings file change. Therefore, my approach was to create a filter that at compile time execute a string find and replace. It's super simple, but useful, at least to me. I also found what I think were a couple of bugs when you had some groups with external_urls defined. When they were missing source_filenames and output_filenames definitions, exceptions were raised when running the management command to compile the source. I put some simple checks in place to safe guard against these exceptions. -
Recompiling Apache on FreeBSD
I am currently working on a Django project that will run on FreeBSD when deployed. I had never worked with this distro before, so it took a bit of getting used to, and I ended up reading man pages and Googling mailing list archives until the wee hours of the morning. One issue that really caught me by surprise was recompiling Apache 2.2 with the proxy modules, so I thought I would jot down my notes here. The solution is pretty simple, but first I have to give some context. If you are not familiar with FreeBSD, it uses a ports & packages analogy for installing software. Their library is pretty good and contained pretty much everything I would need, from mod_python to psycopg2 (I couldn’t use psycopg2 due to a screw-up in their release management and had to settle back to psycopg, but that’s another issue). To compile a port, you basically do this: cd /usr/ports/www/apache22make install clean And that’s it. If the port isn’t there, it’s downloaded and its dependencies are downloaded and compiled as well. Pretty good so far. My problems started when I noticed that Apache 2.2 was not compiled with the proxy modules. So I … -
Nuevo sitio web para django-thumbs
django-thumbs ya tiene nuevo sitio web: http://djangothumbnails.com. La versión 0.3 de django-thumbs funciona correctamente con la versión de desarrollo de Django actual y soluciona algunos problemas de las versiones anteriores. django-thumbs permite crear miniaturas de imágenes para los campos ImageField de tus modelos. -
{% media %}
Незабвенный герой Анатолия Папанова говаривал, что ежели человек идиот, то это надолго. Мне сейчас кажется, что я как раз в такой ситуации :-). Это я о том, как в джанговских шаблонах делать ссылки на JS, CSS и прочую media. Я всегда пропагандировал простой способ: прокидывать в шаблоны переменную MEDIA_URL, используя стандартный контекст-процессор media. А в шаблоне просто составлять слова рядом: <link rel="stylesheet" href="{{ MEDIA_URL }}css/style.css"> Это типа работает, но у такого способа есть пара минусов: Нужно всегда использовать RequestContext для шаблонов. Что, впрочем, в принципе хорошая идея, поэтому минус этот условный. Вот что реально плохо, это что эту переменную приходится вручную прокидывать в любой inclusion-тег, в котором понадобилась media. Это особенно неприятно, потому что периодически мешает параллельности работы верстальщика и программиста. И тут вдруг у меня сошлись в голове какие-то правильные мысли с разных сторон, и я написал себе удобный тег для формирования ссылок на media-файлы в шаблонах с парой полезных дополнений. В простейшем случае он просто присоединяет имя файла к MEDIA_URL: {% media "images/edit.png" %} Однако если параметр начинатся со слеша или с протокола ("http://"), то он уже не будет присоединяться к MEDIA_URL. Можно добавить флажок, чтобы ссылка всегда была абсолютной: <!-- /media/edit.png становится http://example.com/media/edit.png --> {% media "images/edit.png" … -
{% media %}
Незабвенный герой Анатолия Папанова говаривал, что ежели человек идиот, то это надолго. Мне сейчас кажется, что я как раз в такой ситуации :-). Это я о том, как в джанговских шаблонах делать ссылки на JS, CSS и прочую media. Я всегда пропагандировал простой способ: прокидывать в шаблоны переменную MEDIA_URL, используя стандартный контекст-процессор media. А в шаблоне просто составлять слова рядом: <link rel="stylesheet" href="{{ MEDIA_URL }}css/style.css"> Это типа работает, но у такого способа есть пара минусов: Нужно всегда использовать RequestContext для шаблонов. Что, впрочем, в принципе хорошая идея, поэтому минус этот условный. Вот что реально плохо, это что эту переменную приходится вручную прокидывать в любой inclusion-тег, в котором понадобилась media. Это особенно неприятно, потому что периодически мешает параллельности работы верстальщика и программиста. И тут вдруг у меня сошлись в голове какие-то правильные мысли с разных сторон, и я написал себе удобный тег для формирования ссылок на media-файлы в шаблонах с парой полезных дополнений. В простейшем случае он просто присоединяет имя файла к MEDIA_URL: {% media "images/edit.png" %} Однако если параметр начинатся со слеша или с протокола ("http://"), то он уже не будет присоединяться к MEDIA_URL. Можно добавить флажок, чтобы ссылка всегда была абсолютной: <!-- /media/edit.png становится http://example.com/media/edit.png --> {% media "images/edit.png" … -
{% media %}
Незабвенный герой Анатолия Папанова говаривал, что ежели человек идиот, то это надолго. Мне сейчас кажется, что я как раз в такой ситуации :-). Это я о том, как в джанговских шаблонах делать ссылки на JS, CSS и прочую media. Я всегда пропагандировал простой способ: прокидывать в шаблоны переменную MEDIA_URL, используя стандартный контекст-процессор media. А в шаблоне просто составлять слова рядом: <link rel="stylesheet" href="{{ MEDIA_URL }}css/style.css"> Это типа работает, но у такого способа есть пара минусов: Нужно всегда использовать RequestContext для шаблонов. Что, впрочем, в принципе хорошая идея, поэтому минус этот условный. Вот что реально плохо, это что эту переменную приходится вручную прокидывать в любой inclusion-тег, в котором понадобилась media. Это особенно неприятно, потому что периодически мешает параллельности работы верстальщика и программиста. И тут вдруг у меня сошлись в голове какие-то правильные мысли с разных сторон, и я написал себе удобный тег для формирования ссылок на media-файлы в шаблонах с парой полезных дополнений. В простейшем случае он просто присоединяет имя файла к MEDIA_URL: {% media "images/edit.png" %} Однако если параметр начинатся со слеша или с протокола ("http://"), то он уже не будет присоединяться к MEDIA_URL. Можно добавить флажок, чтобы ссылка всегда была абсолютной: <!-- /media/edit.png становится http://example.com/media/edit.png --> {% media "images/edit.png" …