Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Nowa wersja bloga - czyli jak stworzyłem bloga marzeń
Przez ostatni czas przepisywałem tego bloga na django 1.0. Gdy pisałem go około 1.5 roku temu, miałem małe pojęcie o django i python, teraz gdy nabrałem trochę doświadczenia z django i python'em, postanowiłem sobie napisać swojego bloga marzeń. Ktoś mógł by powiedzieć po co pisać bloga od podstaw, przecież można skorzystać z jakiegoś gotowca, jednak ja to traktuje jako takie poletko doświadczalne, miejsce gdzie mogę poeksperymentować z nowymi bibliotekami, narzędziami itd. Pozwala to na nauczenie się czegoś nowego, na co nie koniecznie ma się czas podczas co dziennej pracy zawodowej oraz przekazanie zdobytej wiedzy społeczności. Mój nowy blog posiada następujące funkcje: Autoryzacja wykorzystując django-clickpass django-clickpass jest jednym z projektów ostatnio udostępnionych przez washingtontimes. Implementuje mechanizm autoryzacji clickpass. Clickpass pozwala na logowanie z hotmail, yahoo, google, facebook, aim, clickpass lub OpenID. Zasada działania: Wejście na stronę Przycisk Clickpass ładuje uzupełniony formularz zawierający OpenID użytkownika Użytkownik klika w przycisk Jeżeli logujemy się pierwszy raz, clickpass zapyta czy mamy już konto w jednym z popularnych serwisów, jeżeli tak, to przekieruje do autoryzacji w tym serwisie, następnie wygeneruje OpenID i skojarzy je z serwisem który wybraliśmy. OpenID jest wysłane bezpośrednio przez Clickpass do twojej strony Następuje proces autoryzacji OpenID jak przy zwykłym OpenID Dzięki … -
Using dynamic themes in django
I’ve been working on a django blogger clone. It has many interesting features includding email blogging, gadgets, followers, many authors per blog, feed agregation, fully customizable colors and themes. This time I want to write how do we (I was working with a classmate) solved the problem of dynamic themes. First we wanted the themes to be dynamic that means the site administrator can add or edit themes using the django administration site. First we created a model called Theme class Theme(models.Model): name = models.CharField(max_length=40, unique=True) description = models.TextField(blank=True) slug = models.SlugField(max_length=50, unique=True, editable=False) base_html = models.FileField(upload_to=upload_to('themes/')) style_css = models.FileField(upload_to=upload_to('themes/'), blank=True, null=True) preview = models.ImageField(upload_to=upload_to('themes/')) def __unicode__(self): return '%s' % self.name The name, description, preview and slug fields are obvious. We included a base_html file wich is supoused to be a base template used for all the weblog templates. A css style file is also needed for styling the weblog. Many themes require adicional images so we created another model like this: class ImageTheme(models.Model): theme = models.ForeignKey(Theme) image = models.ImageField(upload_to=upload_to_image('themes/')) We expected each base.html to declare a content, and a sidebar block. So this blocks are used in the weblog templates to display the information. The trick is to pass … -
Django Toronto Meetups
Tonight was the latest in a series of get togethers among Django developers in the Toronto area. We have been doing these for the past few months, since October 2008, and even though our numbers haven’t grown much, I am pretty sure there are other Djangonauts in Toronto who would be interested. We are planning to do monthly scheduled meetings with proper presentations at the Linux Caffe first Wednesday of every month. So join the mailing list and let’s start organizing! Visit the bookmark » -
Schema Migrations with South
For the past few months, I have been trying out the different schema migration tools for Django. At first, the obvious choice seemed like django-evolution. It was the oldest and the most mature project, and after watching the schema evolution panel from DjangoCon 2008, it was also the one that made most sense in terms of architecture. After working with django-evolution in a few projects though, I found that it did not work well in practice. I have recently been testing South, and it seems like the better choice. I had a few big issues with django-evolution: Inability to go backwards or forwards, or to be able to skip migrations (or mutations as it calls them) Inability to use custom fields that require additional parameters Lack of integration with syncdb (if someone in the team accidentally does a syncdb, it fails) I love how clever evolution can be when guessing the modifications to a model, but I don’t think what’s needed from a migration tool is cleverness. I needed a tool that gave me the freedom to do whatever I wanted, while making my job easier by managing all the changes. I have been playing around with South for the … -
Lessons Learned: Google App Engine + App Engine Patch + Django + Boto
Update: Mitch Garnaat from CloudRight has pointed out that you can actually set the policy of the S3 file in the set_contents_from_file call instead of making another roundtrip request into S3 (and saving you some coin). Thanks Mitch! Btw, I’m using App Engine Patch 1.0 and Boto 1.6a. Sorry I haven’t updated my blog in a few weeks months, but I’ve been a little busy. With that said, along with Erlang, I’ve been playing around with Google App Engine, App Engine Patch (for Django support), and the Boto library (for Amazon S3 support). After not having touched Python code in a few months, I wanted to document some of my lessons learned to help over developers who may be in a similar boat. Lessons learned If you’re upgrading the App Engine Patch, make sure you don’t have the App Engine library installed in a hidden directory Uploading bulk data changed ever so slightly If you’re not running off of Boto’s trunk, you’ll need to patch your Boto installation to work with App Engine. Make sure the App Engine library isn’t installed in a hidden directory Apparently, Google’s SDK 1.1.9 doesn’t like to rely on files that won’t be uploaded with … -
Django and mod_wsgi
Finally, Django’s recommended deployment method switched from mod_python to mod_wsgi. Updated docs are now online. Visit the bookmark » -
Django talk at FOSSLC Summercamp/Geocamp 2009
I will be giving an introductory Django talk at The Free and Open Source Software Learning Centre (FOSSLC) Summercamp/Geocamp 2009 Conference. The conference is taking place on May 13, 14, and 15 at Algonquin College, Ottawa, Ontario, Canada, and early bird pricing is available until April 5. -
Google Gets Into VC Business
Recently all the major news papers have covered the same story. Google is getting into the VC space. Its nice to know the company that saved the web is now saving the VC market. Although I expected some new cool social investment platform instead of a simple. "We’ve got $100 Million to [...] -
Templatetags globales en nuestros proyectos Django
Los templatetags de Django son a nivel de aplicación. Sin embargo a veces nos gustaría que distintas aplicaciones compartieran templatetags ó evitarnos tener que cargarlos en todas las plantillas mediante {% load ... %}. Este sencillo snippet muestra cómo registrar templatetags de modo global para todo el proyecto gracias a la función add_to_builtins de django.template. -
Simplifying web development with django-mediasync
One of the more frustrating aspects of programming for the web is managing the development and deployment of static assets. Everything is fine until your site goes live... then you have to deal with images, CSS, and JavaScript staying in sync and being called correctly from either the dev or production instance. Here in the Labs we host all of our production static content on Amazon S3. Updating an existing site involves either changing static files on the production site before the code is launched or changing script and link URLs to point locally during development... remembering to change everything back when the code is pushed out. This process causes much frustration among developers and designers as people often lose track of where things are pointing and the current state of content. To make life easier on everyone, we've developed django-mediasync to manage the deployment of our media content. Develop locally, then when the code is ready for production run mediasync to push static media to S3. mediasync will take care of: running gzip+jsmin on JavaScript files running gzip+cssmin on CSS files adding expires headers to everything (default of 1 year) rewriting the CSS files to use the S3 media … -
Django, mod_python и virtualenv
Небольшая заметка для себя и для тех, кто все еще использует mod_python. Для использования virtualenv с mod_python нужно создать файл в virtualenv bin директории, например, myvirtualdjango.py: #myvirtualdjango.py activate_this = '/home/django/progopedia.ru/ve/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) from django.core.handlers.modpython import handler В конфигурационном файле apache в PythonPath нужно добавить bin директорию virtualenv и установить для PythonHandler значение myvirtualdjango (пример скопирован из реального httpd.conf): <VirtualHost 127.0.0.1:81> ServerName progopedia.ru ServerAdmin admin@progopedia.ru <Location "/"> SetHandler python-program PythonPath "['/home/django/progopedia.ru/ve/bin', '/home/django/progopedia.ru/src/progopedia_ru_project/'] + sys.path" PythonHandler myvirtualdjango SetEnv DJANGO_SETTINGS_MODULE settings SetEnv PYTHON_EGG_CACHE /var/tmp/egg PythonInterpreter polyprog_ru </Location> </VirtualHost> -
Misleading ImportErrors in Django
I was debugging an issue with our Django app at work today; an admin.py file wasn't being picked up, and nothing was appearing in the admin pages. It turned that an ImportError was being thrown in the admin.py and Django was interpreting this as the file not existing. I'm assuming that the reason for this is that Django uses __import__ to import the module, and catches ImportError's if the admin.py doesn't exist. The trouble with this is that if admin.py does exist, and throws an ImportError of its own, Django will also interpret that as a missing admin.py – which can be misleading. The only solution I can think of to more accurately handle this would be to programmaticaly examine the traceback to determine where the ImportError is thrown. If the traceback is one level deep, we know that the ImportError was thrown because the module doesn't exists. If it is greater than one level then we know the module was found, but has thrown an ImportError of its own. Here's a simple proof of concept: #check_import.py import traceback import sys def check_import(name): try: __import__(name) except ImportError: exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() return len(traceback.extract_tb(exceptionTraceback)) > 1 return True print check_import("os") … -
UUID template tag for Django
A while back, I had posted a template tag on djangosnippets which generates UUIDs on the fly. I figured that I’d share the same snippet here and explain why I did it. My rationale for writing this: I needed a quick way to generate random IDs to assign to dynamically generated HTML elements and then […] -
Misleading ImportErrors in Django
I was debugging an issue with our Django app at work today; an admin.py file wasn't being picked up, and nothing was appearing in the admin pages. It turned that an ImportError was being thrown in the admin.py and Django was interpreting this as the file not existing. I'm assuming that the reason for this is that Django uses __import__ to import the module, and catches ImportError's if the admin.py doesn't exist. The trouble with this is that if admin.py does exist, and throws an ImportError of its own, Django will also interpret that as a missing admin.py – which can be misleading. The only solution I can think of to more accurately handle this would be to programmaticaly examine the traceback to determine where the ImportError is thrown. If the traceback is one level deep, we know that the ImportError was thrown because the module doesn't exists. If it is greater than one level then we know the module was found, but has thrown an ImportError of its own. Here's a simple proof of concept: #check_import.py import traceback import sys def check_import(name): try: __import__(name) except ImportError: exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() return len(traceback.extract_tb(exceptionTraceback)) > 1 return True print check_import("os") … -
ORM Panel Recap
Having now completed what I thought was a quite successful panel I thought it would be nice to do a review of some of the decisions I made, that some people had been asking about. For those who missed it you can find a live blog of the event by James Bennett at his blog, and a video should hopefully be going up sometime soon.Why Google App EngineAs Guido pointed out App Engine does not have an ORM, as App Engine doesn't have a relational datastore. However, it does have something that looks and acts quite a lot like other ORMs, and it does fundamentally try to serve the same purpose, offering a persistence layer. Therefore I decided it was at least in the same class of items I wanted to add. Further, with the rise of non-relational DBs that all fundamentally deal with the same issues as App Engine, and the relationship between ORMs and these new persistence layers I thought it would be advantageous to have one of these, Guido is a knowledgeable and interesting person, and that's how the cookie crumbled.Why Not ZODB/Storm/A Talking PonyTime. I would have loved to have as many different ORMs/things like them … -
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 -
Migrating from django-photologue 1.x to 2.x
We're in the process of updating a web app for a client that was built last year about this time using Django and Photologue. Needless to say, there have been a lot of changes to both over the past year! -
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'ы храните в базе, вместо файлов, либо у вас в модели куча полей, которые можно и нужно разнести по разным моделям, провязанным один-к-одному. Впрочем, ладно, разберемся :-) Еще одна фичка, про которую я даже не знал, пока в релиз нотах не прочитал — массовые действия над объектами в админке. Тоже давно просили все, чтобы массово что-нибудь удалять или проставлять флажки всякие. Что меня реально порадовало — это то, что фича сразу вышла хорошо проработанной в деталях: можно выдать юзеру свое сообщение типа "удалено столько-то объектов" можно вместо …