Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Signal vs overriding save
I'm a big fan of signals and wonder why people are so adverse to using them, preferring overriding save instead. -
Django - autoryzacja przez Clickpass - tutorial
Clickpass umożliwia proste logowanie użytkowników za pomocą kont które już posiadają w innych systemach, np. hotmail, yahoo, google, facebook, aim, clickpass lub OpenID. Zasadę działania opisywałem w poprzednim poście. Teraz pokaże jak zaimplementować to w Django. Korzystam z aplikacji która ostatnio udostępniło washingtontimes, a mianowicie django-clickpass. Jest to aplikacja która bardzo upraszcza wykorzystanie clickpass w django. Instalacja Zainstaluj django-openid: svn co http://django-openid.googlecode.com/svn/trunk/django_openid django_openid Zainstaluj paczkę python OpenID 2.2.1 - http://openidenabled.com/files/python-openid/packages/python-openid-2.2.1.tar.gz. Szczegółowe instrukcje znajdziesz tutaj: http://www.openidenabled.com/python-openid/ Dodaj django_openid do Twoich INSTALLED_APPS. Zainstaluj django-clickpass: svn co http://opensource.washingtontimes.com/projects/public/django-clickpass/trunk/clickpass clickpass Dodaj clickpass do Twoich INSTALLED_APPS. Do głównych urls.py dodaj from clickpass.consumer import ClickPassConsumer Dodaj (r'^openid/(.*)', ClickPassConsumer()), do Twoich urlpatterns w urls.py: Przykład urls.py, do dodaniu ClickPassConsummer: from clickpass.consumer import ClickPassConsumer urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^moja_aplikacja/', include('moj_projekt.moja_aplikacja.urls')), (r'^openid/(.*)', ClickPassConsumer()), ) Dodaj clickpass.consumer.ClickPassConsumer do MIDDLEWARE_CLASSES gdzieś po django.contrib.sessions.middleware.SessionMiddleware, np: Przykład: MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'clickpass.consumer.ClickPassConsumer', 'django_openid.consumer.SessionConsumer', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', ) W szablonach możesz dodać przycisk clickpass za pomoca template tag'a clickpass_button_large* lub clickpass_button_small. {% load clickpass %} {% if user.is_anonymous %} Zaloguj się {% clickpass_button_small %} {% else %} Zalogowano jako: {{user.first_name}} {{user.last_name}} {% endif %} Możesz także napisać kilka domyślnych szablonów które używa django-openid. Szablony są w katalogu: django_openid/templates/django_openid Konfiguracja konta clickpass Załóż tzw. … -
Django/Dojo Stammtisch in Berlin
For the second time Django enthusiasts are meeting in Berlin on Wednesday, the 15th April, 2009 at 19:30. Find all the details here. And since I will be in Berlin this time, I just simply redeclare this to “Django/Dojo Stammtisch” instead of just “Django Stammtisch” :-). I hope all the djangoers are ok with that (I requested permission in #django-de). It just makes things easier to also meet some dojo people in Berlin. I will also have some cool new dojango stuff to show off! So if AJAX, JavaScript and Dojo people are around, it would be cool to meet you there and chat about what’s hot and how the beer is. Please add yourself to the attendees list on doodle. And thanks again to the Berlin djangoers for organizing this, I am looking forward to it. -
The Django Deployment Survey - How Are You Hosting Django Websites?
According to the official Django Documentation, there are around a half-dozen documented and supported ways of deploying Django in production environments. The recommended way these days is with Apache and mod_wsgi, but there are still a whole bunch of decisions that one must make when it comes to making their Django project public. One of the great things about running DjangoSites is that it has exposed me to a number of fantastic Django-powered websites. Each of these is unique in one way or another, but they are all running Django. How they use it, though, is anybodies guess. So what are our peers doing? There are proponents for and against each of the different pieces of the Django Deployment puzzle. What operating system should be used? BSD, Linux or Windows? What Database system should be used? Postgres, MySQL, or something else? Which web server software? Apache, nginx, or one of the many python-powered web servers? Which method should I use? mod_python, FastCGI, or something else? Which version of Django? Do I stick to a release, or try and keep up with SVN? To see what our Django-using peers are doing, I am starting a survey of Django website deployment methods. … -
The Django Deployment Survey - How Are You Hosting Django Websites?
According to the official Django Documentation, there are around a half-dozen documented and supported ways of deploying Django in production environments. The recommended way these days is with Apache and mod_wsgi, but there are still a whole bunch of decisions that one must make when it comes to making their … -
A Django deployment guide for Ubuntu
There's a time when every Django developer has to think about deployment scenarios, when I first did it last year I thought that a setup involving Lighty, Apache, mod_proxy and mod_python was a good choice but my first approach was not the best. I put Apache as the front server, handling requests for Django generated pages and passing, via mod_proxy, requests for static content to Lighty on the back. A setup where Apache had to work even for files that wasn't supposed to serve was a very bad idea. After many helpful comments and some more reading I realized that it was better having the server for static content on the front and Apache, which still talks to Django, on the back. I replaced Lighty with nginx, which according to many seems to be more stable, and opted for mod_wsgi instead of mod_python to make Apache talk to Django. mod_wsgi has a lower memory overhead and it's suitable for high performance sites. There's no need for mod_proxy on Apache anymore as nginx is the one in charge of the proxy work now. This is an easy to follow and very focused guide for developers who know how to handle their … -
A Django deployment guide for Ubuntu
January 2012 update: I use and recommend gunicorn and Nginx for Django projects now. There's a time when every Django developer has to think about deployment scenarios, when I first did it last year I thought that a setup involving Lighty, Apache, mod_proxy and mod_python was a good choice but my first approach was not the best. I put Apache as the front server, handling requests for Django generated pages and passing, via mod_proxy, requests for static content to Lighty on the back. A setup where Apache had to work even for files that wasn't supposed to serve was a very bad idea. After many helpful comments and some more reading I realized that it was better having the server for static content on the front and Apache, which still talks to Django, on the back. I replaced Lighty with nginx, which according to many seems to be more stable, and opted for mod_wsgi instead of mod_python to make Apache talk to Django. mod_wsgi has a lower memory overhead and it's suitable for high performance sites. There's no need for mod_proxy on Apache anymore as nginx is the one in charge of the proxy work now. This is an easy … -
Django like templates in Javascript
Here's a quick ‘n’ dirty Javascript function I hacked together that provides Django-like template substitution. function sformat(template, data) { return template.replace(/{{(.*?)}}/g, function(m, n) { return eval('data.'+n); }); } Used something like this: sformat("Hello, {{ name }}!", {name:"World"}); Which returns the following string: Hello, World! Alas, it doesn't support anything other than substitution. If you need anything more advanced (loops etc), you should investigate Javascript template engines. -
Django like templates in Javascript
Here's a quick ‘n’ dirty Javascript function I hacked together that provides Django-like template substitution. function sformat(template, data) { return template.replace(/{{(.*?)}}/g, function(m, n) { return eval('data.'+n); }); } Used something like this: sformat("Hello, {{ name }}!", {name:"World"}); Which returns the following string: Hello, World! Alas, it doesn't support anything other than substitution. If you need anything more advanced (loops etc), you should investigate Javascript template engines. -
Django like templates in Javascript
Here's a quick ‘n’ dirty Javascript function I hacked together that provides Django-like template substitution. function sformat(template, data) { return template.replace(/{{(.*?)}}/g, function(m, n) { return eval('data.'+n); }); } Used something like this: sformat("Hello, {{ name }}!", {name:"World"}); Which returns the following string: Hello, World! Alas, it doesn't support anything other than substitution. If you need anything more advanced (loops etc), you should investigate Javascript template engines. -
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 …