Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Full-text search across multiple Django models using Djapian/Xapian
I recently implemented full text search in my Django web application. I am a big fan of the Xapian search engine library so I was extremely thrilled to find the Djapian project. Djapian is a Django app that enables indexing and searching of your Django models. One of the major requirements I had for my search [...] -
Expires headers lejanos y versiones de media
Un buen truco para mejorar el tiempo de carga de nuestras páginas es añadir a los archivos de media (imágenes, css, js) el header Expires (ver headers de HTML) con una fecha lejana (por ejemplo un año de diferencia). Este header define cuándo expira el archivo, es decir, hasta cuando el navegador puede considerar la respuesta del archivo válida. Esto significa que cuando el navegador descarga un archivo con header Expires puede almacenarlo en caché y utilizarlo sin tener que volver a descargarlo otra vez cuando el usuario visite de nuevo el sitio web, hasta que llegue la fecha descrita en el header Expires ... -
Migración de esquemas con django-evolution
Las migraciones o evoluciones de esquema son las modificaciones que hacemos a modelos ya creados y que afectan a la base de datos. Cuando sincronizamos por primera vez los modelos de nuestra aplicación mediante syncdb se crean las tablas necesarias para los mismos en la base de datos. Si tras esto realizamos cambios en nuestros modelos tendremos que ejecutar el comando manage.py reset aplicacion para que se borren las tablas correspondientes a nuestra aplicación y vuelvan a crearse nuevas tablas a partir de los nuevos modelos. El problema se nos plantea cuando tenemos que realizar cambios en modelos que ya estamos utilizando para almacenar datos y por lo tanto no podemos eliminar sus tablas para volver a crearlas. Esto ocurre sobre todo en los entornos de producción. Las soluciones principales son 2: Modificar nuestro modelo y realizar manualmente los cambios equivalentes en sus respectivas tablas de la base de datos ó utilizar alguna herramienta de migración de esquemas como django-evolution, South ó dmigrations. Vamos a ver cómo usar django-evolution para realizar nuestras migraciones de esquema de una forma sencilla. -
Getting the client IP address behind a proxy in Apache
Typically in my Django projects deployments I use Nginx as a front-end web server to handle static content while proxying all other requests to Apache. When the request arrives to Apache, the client IP address is 127.0.0.1. We need to configure Apache to accept the IP address from X-Real-IP or X-Forwarded-For headers set by Nginx. To solve this problem I use mod_rpaf that does exactly the opposite of mod_proxy_add_forward. In my Nginx virtualhost configuration I have something like: server { ... location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ... } ... } This also applies if your are using a different webserver as front-end such as Lighttpd or another instance of Apache. -
Getting the client IP address behind a proxy in Apache
Typically in my Django projects deployments I use Nginx as a front-end web server to handle static content while proxying all other requests to Apache. When the request arrives to Apache, the client IP address is 127.0.0.1. We need to configure Apache to accept the IP address from X-Real-IP or X-Forwarded-For headers set by Nginx. To solve this problem I use mod_rpaf that does exactly the opposite of mod_proxy_add_forward. In my Nginx virtualhost configuration I have something like: server { ... location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ... } ... } This also applies if your are using a different webserver as front-end such as Lighttpd or another instance of Apache. -
Escribir comandos de administración en Django
Muchas veces nos gustaría crear comandos propios que puedan ejecutarse mediante django-admin.py ó el manage.py de nuestro proyecto. Django permite crear comandos de administración específicos para cada aplicación de nuestro proyecto. Para crear comandos específicos, dentro de la carpeta de nuestra aplicación debemos crear un directorio llamado management y dentro de éste otro llamado commands ... -
Useful Django API's
Two useful Django API's that I've found today. -
X-UA-Compatible Django Middleware
When Microsoft's Internet Explorer 8 was released this past March, it included a fairly decent standards-compliant rendering engine. While a step forward for the web, a compliant rendering engine breaks many web sites that were developed for previous versions of IE. Internal corporate and government networks are notorious for sites that were built for IE 6 or 7 and often took advantage of bugs in the rendering engines. To prevent these sites, and others across the web, from breaking, IE 8 will sometimes use one of the older rendering engines. There are various conditions that are used to select the engine that will be used to render the page. The good news is that you, as a web developer, can instruct IE 8 to use a specific engine to render your site. This can be done by using the X-UA-Compatible HTTP header or HTML meta tag. Sunlight Labs has written middleware and a decorator for Django that will take care of sending the appropriate HTTP header. Include the following in settings.py to enable the middleware: MIDDLEWARE_CLASSES = ( ... 'compatibility.XUACompatibleMiddleware', ) The middleware will send a default X-UA-Compatible header of IE=edge for any HTML or XHTML response. The default value … -
Django Dash 2009
El 30 de mayo comenzará Django Dash. Se trata de una competición en la que hay que desarrollar la mejor aplicación web que se pueda en tan sólo 48 horas, obviamente, con Django. Se pueden inscribir equipos de hasta 3 personas. La inscripción se cierra dentro de 5 días. El equipo ganador obtendrá diversos premios... -
Portuguese Python User Group
I've created a Python User Group in Portugal. The idea is to join people who enjoy programming in Python. No membership is required to participate, experienced programmers and absolute beginners are both welcome! You can visit the site or follow us on Twitter. -
Portuguese Python User Group
I've created a Python User Group in Portugal. The idea is to join people who enjoy programming in Python. No membership is required to participate, experienced programmers and absolute beginners are both welcome! You can visit the site or follow us on Twitter. -
Review of Django 1.0 Template Development
Initially when Packt Publishing sent this ebook Django 1.0 Template Development by Scott Newman to review, I did what any self respecting Django entreprenuer with 3 project down his pants would do. I skimmed through the book to the code sections and read through the code and read about 10 lines after that. The blink that I obtained reading the book this way was not too good and I felt some of the explanation in certain sections lacking. BAD mistake! This book SHOULD NOT and I repeat SHOULD NOT be read that way. After I hunkered down and read the book cover to cover, it was then I really began to like it. So now, Django projects later, I wish that I read the book the right way the first time, because it has given me so many ideas to improve my Django code. So my advice, get this book, read it cover to cover and then revisit, bookmark or underline sections that you will revisit later. This way I found out was the way to get the maximum benefit out of this great Django reference. I really like reading technical books that know how to put forth advanced concepts … -
Django 1.1 Talk Text
This is the text from the Django 1.1 talk I gave on Friday May 15 at Algonquin College for FOSSLC's Geocamp/Summercamp 2009. I have tried to format this in a way that is well suited to skimming and easier to access from the web than reading the original slides. If you find this useful, please let me know. -
Seattle Django Users’ group
A Seattle Django Users’ group is forming. Here’s the official announcement: —— Forwarded Message From: Brian Gershon Reply-To: A group of Python users in Seattle Date: Mon, 4 May 2009 13:57:35 -0700 To: seattle-python, plone_seattle Subject: New Seattle Django User Group meeting June 2 (Save the Date) This is an invite for the newly forming [...] -
Виджет на морде
Как же сложно писать о том, что заняло у тебя столько сил и эмоций. Очень многое хочется рассказать, но почему-то трудно сформулировать и четко выразить мысль. Наверно это эмоции и неравнодушие так проявляются. Но я всё равно попробую. Обновленная Яндекс.Афиша работает на Джанге. Вот уже третий месяц как. Запустили мы её прямо в канун пятницы тринадцатого в марте! Проект получился большой, со своими особенностями. Расскажу вам про процесс разработки с допустимой детальностью. Глобальная цель была - обновить движок Яндекс.Афиши, переписав его на Django. Что да как Распил кода КВИ Ни для кого не секрет, что сервис "Куда все идут" один из сервисов Яндекса написанных на Джанге. Долгое время он был дополнением к Афише и добавлял социальный фан для пользователей. Ему и было суждено дать начало новой Афише. Мы резонно решили, что, переписывая Афишу на Джанге, нужно опираться уже на имеющийся code base КВИ. Но при разработке КВИ никто и не думал, что в последствие этот код может быть использован в другом проекте, поэтому процесс отделения и обобщения имеющихся наработок занял много времени и сил. Тогда мы впервые начали использовать наследование моделей в Джанге, т.к. многие наши сущности можно было строго разделить на общие части и какие-то сервисо-зависимые надстройки. Это кстати … -
Bericht vom dritten Django-UserGroup Treffen in Hamburg
Am Dienstag, den 12.05.2009, hat sich die Django-UserGroup Hamburg zum dritten Mal getroffen. Dank der CoreMedia AG hatten wir diesmal einen Raum mit Beamer und W-Lan zur Verfügung, so dass wir eine Reihe kurzer Vorträge halten bzw. hören konnten. Wenn wir uns nicht verzählt haben waren 17 Djangonauten anwesend. Die Vorträge orientierten sich am Format Lightning Talks, so dass jeder der wollte 5 bis 10 Minuten Zeit bekam zu einem Thema seiner Wahl etwas zu erzählen. Folgende Vorträge gab es: Django + PyAMF von @mohlendo RESTful Django am Beispiel routeconverter.com von @cpesch Django-Caching in der Praxis von @_arne [Slides] Deployment mit Fabric von @bracki [Fabric] Vorstellung von kogakure.de von @kogakure Spam-Deathmatch von @toadle [Blog-Eintrag] Des Weiteren haben wir auf dem Treffen entschieden ein Repository auf GitHub anzulegen, in dem wir Slides und Code allen zugänglich machen können. Das Master-Respository ist hier zu finden: http://github.com/mohlendo/dughh/ und zusätzlich gibt es die Domain dughh.de, welche zur Zeit einfach auf das Repository umgeleitet wird. Ausblick Das nächste Treffen wird in ca. 2 Monaten stattfinden, ankündigen werden wir das Treffen rechtzeitig hier im Blog, unter dughh.de in der Django-Gruppe auf Xing, in den News auf django-de.org und auf der django-de GoogleGroup. Jeder der schon vorab … -
¿Cómo agregar editores HTML al django admin?
Django trae una feature que es simplemente genial: interfaz administrativa generada automáticamente como parte del framework. Esta interfaz ahorra mucho tiempo de desarrollo el cual podés usar para dejar mas bonita tu aplicación Django. Esta interfaz se puede customizar hasta … Continue reading → -
¿Cómo agregar editores HTML al django admin?
Django trae una feature que es simplemente genial: interfaz administrativa generada automáticamente como parte del framework. Esta interfaz ahorra mucho tiempo de desarrollo el cual podés usar para dejar mas bonita tu aplicación Django. Esta interfaz se puede customizar hasta cierto punto pero desgraciadamente no trae un editor de HTML WYSIWYGbonito de esos que se usan para poner un post en un blog o foro que permiten que alguien sin conocimientos de HTML pueda dar estilo a lo que escribe de manera sencilla y parecido a una suite ofimática. Para esto tenemos disponibles una gran cantidad de editores hechos en javascriptlibres y gratuitos disponibles en la red. En este caso usaremos mi preferido TinyMCE el cual es muy popular y es el editor por defecto de Wordpress. Este editor funciona con los campos definidos como TextField Paso 1: Bajar TinyMCE Paso 2. En un proyecto de Django agregar la carpeta de TinyMCE a la locación donde guarden su javascript Paso 3. Agregar el siguiente archivo para configurar el aspecto dentro de una carpeta llamada editores (o como quieran ponerle) en la misma ubicación del paso 2. Paso 4. En el admin.py de la aplicación en la cual desean tener el … -
jj: dojo.beer(3) wrap up
jj: dojo.beer(3) wrap up -
Autoryzacja przez clickpass kontra rpx
RPX jest podobną usługą do clickpass - upraszcza logowanie z systemów gdzie użytkownicy już mają konta. Zasada działania jest bardzo podobna. System ten również opiera się o OpenID. Istnieje także implementacja rpx dla django - http://code.google.com/p/django-newrpx/ rpx wydaje się lepsze od clickpass, z tego względu że użytkownik dużo łatwiej się może zalogować, praktycznie po autoryzacji w systemie zewnętrznym jest już zalogowany, przy clickpass po autoryzacji pokazuje się formularz rejestracyjny z wypełnionymi danymi( typu: email, opcjonalnie imię, nazwisko) i trzeba ręcznie wpisać nazwę użytkownika jaki będzie utworzony. W rpx się tego nie robi, wszystko się dzieje z automatu, nazwa użytkownika jest z automatu przekazywana(z systemu w którym wcześniej odbyła się autoryzacja) do backend’u autoryzacji który sam tworzy nowego użytkownika i go loguje. Przy następnym logowaniu backend sprawdza czy login użytkownika(przekazany np. z google accounts) istnieje już i go loguje. W jednym i drugim przypadku logowanie to tak naprawdę 2-3 kliknięcia myszą. Teraz na temat samej implementacji rpx w django Pakiet django-newrpx był dosyć z bugowany – parę drobnych bugów w kodzie, udało mi się wszystko popoprawiać i wysłać pacha do autora. W django-newrpx w przeciwieństwie do django-clickpass nie ma zaimplementowanego tzn "account merge"(samo rpx obsługuje tą opcje- Mapping API) jest to … -
Simple Django Commenting System with Ajax
I have begun incorporating ajax techniques using the script.aculo.us and prototype libraries and thought I'd share a basic example that combines ajax with django. The snippets shown here have been taken and simplified for the purpose of this article. Making good use of ajax can significantly improve the usability of a website as it introduces a more user friendly experience. Granted sites can go overboard especially with all the effects. In this article I thought I would demonstrate a simple commenting system that uses the Prototype library to create asynchronous calls necessary for submitting a form while remaining integrated with the django framework. Model Lets start with the model describing the commenting class. It contains the basics for user submitted comments, name, email, website, content, reference, etc. The key represents an attribute for retrieving a set of comments. For example, combining the comments with articles the key could store the article's title or slug. When an article is loaded the comments can easily be retrieved based on their title. The name, email and website contain information on the user submitting a comment. The email and website fields are optional in this case. The text refers to the comment being submitted … -
Job board added
As promised the site now has a job board -
Customized comment notifications from Django
I recently had to implement a way to send notifications (using the excellent django-notification app developed by James Tauber) to users whose content is commented on in my Django web app. However, I wanted the owner/creator of the original content to get a more customized notification message. For example, if the model instance being commented [...] -
Switching from PHP to Django: The Result
-
Selling clients on Django
So right up front let me just say that I love Django. This should come as no surprise to anyone who has been to my site. I think its a great framework and I really enjoy working with it. That being said all too often my clients look like a deer in headlights when I [...]